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

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BRANCH="${BRANCH:-main}"
SERVICE="eniacventures"
PORT="3011"

cd "$APP_DIR"

if ! git diff --quiet HEAD -- src/routeTree.gen.ts; then
  backup="$(mktemp /tmp/eniacventures-routeTree.XXXXXX)"
  cp -- src/routeTree.gen.ts "$backup"
  git restore --source=HEAD --staged --worktree -- src/routeTree.gen.ts
  echo "Rotas geradas anteriores salvas em $backup"
fi

if [ -n "$(git status --porcelain)" ]; then
  echo "ERRO: checkout contém alterações locais; preserve-as antes do deploy" >&2
  git status --short >&2
  exit 1
fi

git fetch origin "$BRANCH"
git checkout "$BRANCH"
git pull --ff-only origin "$BRANCH"

trap 'git restore --worktree -- package-lock.json' EXIT
npm install --package-lock-only --ignore-scripts --no-audit --no-fund
npm ci --no-audit --no-fund
npm run build
test -f .output/server/index.mjs
for asset in public/media/eniac/*; do
  test -s ".output/public/${asset#public/}"
done

sudo -n /usr/bin/systemctl restart "$SERVICE"
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if curl --fail --silent --output /dev/null "http://127.0.0.1:${PORT}/"; then
    echo "Deploy concluído: $(git rev-parse --short HEAD)"
    exit 0
  fi
  sleep 1
done
echo "ERRO: serviço não respondeu na porta ${PORT}" >&2
exit 1
