#!/usr/bin/env bash
# Manual deploy on NODE Cloud (no CI). Run on the server as root.
set -euo pipefail
APP_DIR="/srv/nodecloud/apps/biztaghavisite"
PORT=3009

cd "$APP_DIR"

echo "==> Pull latest code"
git pull origin main

echo "==> Ensure Docker network"
docker network inspect nodecloud-net >/dev/null 2>&1 || docker network create nodecloud-net

if [[ ! -f .env ]]; then
  echo "ERROR: $APP_DIR/.env missing. Copy from .env.example and fill values."
  exit 1
fi

echo "==> Build image (10–20 min on first run; Liara mirror may be slow)"
docker compose build --no-cache

echo "==> Start MariaDB + app"
docker compose up -d

echo "==> Wait for MariaDB"
for i in $(seq 1 30); do
  if docker compose exec -T db healthcheck.sh --connect --innodb_initialized >/dev/null 2>&1; then
    echo "    MariaDB healthy"
    break
  fi
  sleep 2
done

echo "==> Apply database schema (idempotent)"
set -a
# shellcheck disable=SC1091
source .env
set +a
docker compose exec -T db mariadb -u "${DB_USER:-biztaghavi}" -p"${DB_PASSWORD}" "${DB_NAME:-biztaghavi}" \
  < prisma/migrations/0_init/migration.sql || true

echo "==> Health check"
sleep 3
curl -sf "http://127.0.0.1:${PORT}/" -o /dev/null && echo "OK: app responds on :${PORT}" || {
  echo "FAIL: app not responding"
  docker compose logs --tail=80 next-app
  exit 1
}

curl -sI -H "Host: biztaghavi.com" "http://127.0.0.1/" | head -5
docker compose ps
echo ""
echo "Done. Test https://biztaghavi.com — purge ArvanCloud cache if needed."
echo "Create admin once: curl -X POST https://biztaghavi.com/api/admin/setup ..."
