#!/usr/bin/env bash
# Run this ONCE on the server to bootstrap the biztaghavi app.
# Usage: bash scripts/first-deploy.sh
set -euo pipefail

APP_NAME="biztaghavi"
APP_DIR="/srv/nodecloud/apps/$APP_NAME"
REPO_URL="https://git.nodecloud.ir/biztaghavi/biztaghavisite.git"
NGINX_CONF="/etc/nginx/sites-available/$APP_NAME"
PORT=3009

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║  biztaghavi — First Deploy Bootstrap     ║"
echo "╚══════════════════════════════════════════╝"
echo ""

# ── 1. App directory ─────────────────────────────────────────────────────────
if [ -d "$APP_DIR/.git" ]; then
  echo "[1/7] App directory already exists — skipping clone, pulling latest..."
  cd "$APP_DIR" && git pull origin main
else
  echo "[1/7] Creating $APP_DIR and cloning repository..."
  mkdir -p "$APP_DIR"
  git clone "$REPO_URL" "$APP_DIR"
  cd "$APP_DIR"
fi

# ── 2. Docker network ─────────────────────────────────────────────────────────
echo "[2/7] Ensuring nodecloud-net Docker network exists..."
docker network inspect nodecloud-net >/dev/null 2>&1 \
  && echo "      nodecloud-net already exists" \
  || docker network create nodecloud-net

# ── 3. Environment file ───────────────────────────────────────────────────────
echo "[3/7] Setting up .env file..."
if [ -f "$APP_DIR/.env" ]; then
  echo "      .env already exists — skipping"
else
  cp "$APP_DIR/.env.example" "$APP_DIR/.env"
  echo ""
  echo "  ⚠️  IMPORTANT: Edit $APP_DIR/.env before continuing!"
  echo "      At minimum set: DB_ROOT_PASSWORD, DB_PASSWORD, SESSION_SECRET, SETUP_KEY"
  echo ""
  read -rp "  Press ENTER after you have filled in .env values... "
fi

# ── 4. Nginx config ───────────────────────────────────────────────────────────
echo "[4/7] Installing Nginx config..."
cp "$APP_DIR/nginx/$APP_NAME.conf" "$NGINX_CONF"
ln -sf "$NGINX_CONF" "/etc/nginx/sites-enabled/$APP_NAME"
echo "      Testing Nginx config..."
nginx -t
systemctl reload nginx
echo "      Nginx reloaded"

# ── 5. Build & start containers ───────────────────────────────────────────────
echo "[5/7] Building Docker image (this takes a few minutes)..."
cd "$APP_DIR"
docker compose build

echo "[6/7] Starting services..."
docker compose up -d

# ── 6. Wait for health ────────────────────────────────────────────────────────
echo "[7/7] Waiting for app to become healthy..."
for i in $(seq 1 24); do
  if curl -sf http://127.0.0.1:$PORT/ -o /dev/null 2>&1; then
    echo ""
    echo "✅ App is up at http://127.0.0.1:$PORT"
    break
  fi
  printf "."
  sleep 5
done
echo ""

# ── 7. Summary ────────────────────────────────────────────────────────────────
echo ""
echo "══════════════════════════════════════════"
echo " Next steps:"
echo "  1. Point DNS A record for biztaghavi.com → 193.105.234.35"
echo "  2. Issue SSL:  certbot --nginx -d biztaghavi.com -d www.biztaghavi.com"
echo "  3. Add Gitea secrets (see DEPLOY.md)"
echo "══════════════════════════════════════════"
echo ""
docker compose ps
