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

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

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
test -f .output/server/index.mjs
for asset in public/media/unikko/*; 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
