#!/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
COMPOSE_FILE="docker-compose.yml"
DOCKERFILE_NOTE="online build (Liara npm mirror)"

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

# Offline bundle from Mac (recommended for Iran)
if [[ -f iran-bundle.tar.gz ]]; then
  COMPOSE_FILE="docker-compose.prebuilt.yml"
  DOCKERFILE_NOTE="prebuilt bundle (no npm on server)"
  echo "==> Extract iran-bundle.tar.gz"
  rm -rf iran-bundle
  mkdir -p iran-bundle
  tar -xzf iran-bundle.tar.gz -C .
  if [[ ! -f iran-bundle/standalone/server.js ]]; then
    echo "ERROR: iran-bundle/standalone/server.js missing — re-run bundle-for-iran.sh on Mac"
    exit 1
  fi
else
  echo "WARN: iran-bundle.tar.gz not found — building on server (needs Liara mirror)."
  echo "      Recommended: run scripts/bundle-for-iran.sh on Mac and scp iran-bundle.tar.gz here."
fi

echo "==> Build image ($DOCKERFILE_NOTE)"
docker compose -f "$COMPOSE_FILE" build --no-cache

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

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

if [[ -f prisma/migrations/0_init/migration.sql ]] && [[ -s prisma/migrations/0_init/migration.sql ]]; then
  echo "==> Apply database schema"
  set -a
  # shellcheck disable=SC1091
  source .env
  set +a
  docker compose -f "$COMPOSE_FILE" exec -T db mariadb \
    -u "${DB_USER:-biztaghavi}" -p"${DB_PASSWORD}" "${DB_NAME:-biztaghavi}" \
    < prisma/migrations/0_init/migration.sql || true
else
  echo "WARN: prisma/migrations/0_init/migration.sql missing or empty — skip SQL apply"
fi

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

curl -sI -H "Host: biztaghavi.com" "http://127.0.0.1/" | head -5
docker compose -f "$COMPOSE_FILE" ps
echo ""
echo "Done. Test https://biztaghavi.com (purge ArvanCloud cache if needed)."
