#!/usr/bin/env bash
# CNPERP production deploy helper (run on Hetzner server as user cnperp)
set -euo pipefail
APP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$APP_ROOT"
BRANCH="${1:-main}"

echo "==> CNPERP deploy from origin/$BRANCH"
git fetch origin
git pull origin "$BRANCH"

source .venv/bin/activate
pip install -r requirements.txt --upgrade --quiet

if [ -d migrations ]; then
  for m in migrations/*.py; do
    [ -f "$m" ] || continue
    base=$(basename "$m")
    [[ "$base" == __* ]] && continue
    echo "==> migration $base"
    python "$m" || echo "WARN: $base"
  done
fi

echo "==> restart cnperp"
sudo systemctl restart cnperp
sleep 2
sudo systemctl is-active cnperp && echo "Deploy OK"
