#!/usr/bin/env bash
set -euo pipefail

PANEL_URL="https://simplavende.com.br/suporte/nvr-console-panel-20260612-c0fa52e87e8a.sh"
PANEL_SHA256="c3ae9180341ff3897f6da8a502eacbb9bf72bb9d192ac4a47eee647f9ae431b6"
SERIAL="ACT-NVR-87305B3B"
TMP_PANEL="$(mktemp)"
COOKIE_JAR="$(mktemp)"
BODY_FILE="$(mktemp)"
cleanup() { rm -f "$TMP_PANEL" "$COOKIE_JAR" "$BODY_FILE"; }
trap cleanup EXIT

need_root() {
  if [ "$(id -u)" -ne 0 ]; then
    echo "Execute com sudo: curl -fsSL https://simplavende.com.br/suporte/nvr-panel-hotfix-20260612-c0fa52e87e8a.sh | sudo bash" >&2
    exit 1
  fi
}

need_root
command -v curl >/dev/null 2>&1 || { echo "curl ausente" >&2; exit 1; }
command -v sha256sum >/dev/null 2>&1 || { echo "sha256sum ausente" >&2; exit 1; }

curl -fsSL "$PANEL_URL" -o "$TMP_PANEL"
actual_sha="$(sha256sum "$TMP_PANEL" | awk '{print $1}')"
if [ "$actual_sha" != "$PANEL_SHA256" ]; then
  echo "hash do painel divergente; abortando" >&2
  exit 1
fi
install -o root -g root -m 0755 "$TMP_PANEL" /usr/local/sbin/nvr-console-panel

csrf="$(curl -fsSL -c "$COOKIE_JAR" -b "$COOKIE_JAR" http://127.0.0.1/nvr/cadastro   | sed -n 's/.*name=["'"'"']_token["'"'"'][^>]*value=["'"'"']\([^"'"'"']*\)["'"'"'].*//p; s/.*value=["'"'"']\([^"'"'"']*\)["'"'"'][^>]*name=["'"'"']_token["'"'"'].*//p'   | head -1)"
if [ -z "$csrf" ]; then
  echo "csrf nao encontrado; painel sera reiniciado com fallback visual" >&2
else
  http_code="$(curl -sS -L -o "$BODY_FILE" -w '%{http_code}' -c "$COOKIE_JAR" -b "$COOKIE_JAR"     -X POST http://127.0.0.1/nvr/ativacao     --data-urlencode "_token=$csrf"     --data-urlencode "serial=$SERIAL"     --data-urlencode "activation_code=$SERIAL"     --data-urlencode 'redirect_to=/login' || true)"
  echo "activation_post_http=$http_code"
fi

activation_page="$(curl -fsSL http://127.0.0.1/nvr/ativacao 2>/dev/null || true)"
if printf '%s' "$activation_page" | grep -Eiq 'nvr-activation-success|Appliance pronto|Ativa..o conclu.da'; then
  echo "activation_page=concluida"
else
  echo "activation_page=nao_confirmada"
fi

for state in   /opt/nvr/gateway/storage/cache/gateway-state.json   /opt/nvr/gateway/storage/gateway-state.json   /opt/nvr/storage/gateway-state.json   /var/lib/nvr/gateway-state.json   /var/lib/nvr/state/gateway-state.json; do
  if [ -s "$state" ]; then
    if grep -Eq '"registered"[[:space:]]*:[[:space:]]*true' "$state"; then
      echo "gateway_state=registered ($state)"
    else
      echo "gateway_state=present_not_registered ($state)"
    fi
    break
  fi
done

systemctl daemon-reload || true
systemctl restart nvr-console-panel.service
sleep 2
echo "panel_service=$(systemctl is-active nvr-console-panel.service 2>/dev/null || true)"
echo "hotfix=ok"
