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

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

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
  echo "Build concluído; a unidade será instalada por ops/install-vm-config.sh."
  exit 0
fi
sudo -n /usr/bin/systemctl restart "$SERVICE"
for attempt in $(seq 1 20); 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
