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

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

cd "$APP_DIR"
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"
npm ci --no-audit --no-fund
npm run build

if sudo -n /usr/bin/systemctl cat "$SERVICE" >/dev/null 2>&1; then
  sudo -n /usr/bin/systemctl restart "$SERVICE"
else
  echo "Build concluído; a unidade será provisionada por ops/install-vm-config.sh."
  exit 0
fi
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
