#!/usr/bin/env bash
# Polleo Demand — production deploy (git pull + deps + frontend build + API restart).
#
# Run on the VPS as the polleo user (manually or via GitHub Actions SSH):
#   bash /var/www/html/nabava.polleosport.com/deploy/deploy.sh
#
# Requires passwordless sudo for systemctl restart (see polleo-deploy.sudoers.example).
#
# Optional env vars:
#   APP_DIR=/var/www/html/nabava.polleosport.com
#   DEPLOY_BRANCH=master
#   SMOKE_URL=https://nabava.polleosport.com   # run smoke_test.sh after deploy
#   SMOKE_USER / SMOKE_PW                       # passed to smoke_test.sh

set -euo pipefail

APP_DIR="${APP_DIR:-/var/www/html/nabava.polleosport.com}"
BRANCH="${DEPLOY_BRANCH:-master}"
SERVICE="${SERVICE_NAME:-nabava-api}"

cd "$APP_DIR"

echo "==> Fetching origin/${BRANCH}"
git fetch origin "$BRANCH"
git reset --hard "origin/${BRANCH}"

echo "==> Python dependencies"
# shellcheck disable=SC1091
source .venv/bin/activate
pip install --upgrade pip --quiet
pip install -r requirements.txt --quiet

echo "==> Frontend build"
cd frontend
npm ci
npm run build
cd ..

echo "==> Restarting ${SERVICE}"
sudo systemctl restart "$SERVICE"
sudo systemctl is-active --quiet "$SERVICE"

echo "==> Deploy complete ($(git rev-parse --short HEAD))"

if [[ -n "${SMOKE_URL:-}" ]]; then
    echo "==> Smoke test (${SMOKE_URL})"
    bash deploy/smoke_test.sh "$SMOKE_URL"
fi
