#!/usr/bin/env bash
# =============================================================================
#  Club Management System — Full CapRover Deploy Script
#  Usage:  chmod +x deploy.sh && ./deploy.sh
# =============================================================================
set -e

# ─── CONFIGURATION ───────────────────────────────────────────────────────────
CAPROVER_URL="http://captain.caprover.al-arcade.com"
CAPROVER_PASSWORD="Alarcade123#"
APP_NAME="club-management-club"
GITLAB_REPO="http://gitlab.caprover.al-arcade.com/root/finalclubmanagementphp.git"
GITLAB_USER="root"
GITLAB_TOKEN="vHATWUzqfUC1nkXkGkai"

# Existing DB server
DB_HOST="srv-captain--mysql-db"
DB_PORT="3306"
DB_NAME="club_membership"
DB_USER="root"
DB_PASS="Alarcade123#"
APP_URL="https://${APP_NAME}.caprover.al-arcade.com"

# ─── COLORS ──────────────────────────────────────────────────────────────────
GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
info()  { echo -e "${GREEN}[INFO]${NC}  $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }

# ─── 1. PREREQUISITES ────────────────────────────────────────────────────────
info "Checking prerequisites..."

if ! command -v node &>/dev/null; then
    info "Installing Node.js 20..."
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
    apt-get install -y nodejs
fi
node -v

if ! command -v caprover &>/dev/null; then
    info "Installing CapRover CLI..."
    npm install -g caprover
fi
caprover --version

command -v git &>/dev/null || { apt-get update && apt-get install -y git; }
command -v curl &>/dev/null || { apt-get update && apt-get install -y curl; }

# ─── 2. CLONE REPO ───────────────────────────────────────────────────────────
DEPLOY_DIR="/tmp/club_deploy_$(date +%s)"
info "Cloning repository to ${DEPLOY_DIR}..."
git clone "http://${GITLAB_USER}:${GITLAB_TOKEN}@$(echo $GITLAB_REPO | sed 's|http://||')" "$DEPLOY_DIR"
cd "$DEPLOY_DIR"

# ─── 3. SAFETY CLEANUP ───────────────────────────────────────────────────────
info "Removing sensitive/dead files..."
rm -f code.sql
rm -f core/App_112.php core/Database_110.php core/View_111.php core/helpers_109.php
rm -rf prompts/

# ─── 4. GET CAPROVER JWT TOKEN ───────────────────────────────────────────────
info "Authenticating with CapRover API..."
TOKEN=$(curl -sf -X POST "${CAPROVER_URL}/api/v2/login" \
  -H "Content-Type: application/json" \
  -d "{\"password\":\"${CAPROVER_PASSWORD}\"}" \
  | grep -o '"token":"[^"]*"' | cut -d'"' -f4)

[ -z "$TOKEN" ] && error "Auth failed. Check CAPROVER_URL and CAPROVER_PASSWORD."
info "Authenticated OK."

# ─── 5. CREATE APP (idempotent — ignores error if already exists) ────────────
info "Creating CapRover app '${APP_NAME}'..."
curl -sf -X POST "${CAPROVER_URL}/api/v2/user/apps/appDefinitions/register" \
  -H "Content-Type: application/json" \
  -H "x-captain-auth: ${TOKEN}" \
  -d "{\"appName\":\"${APP_NAME}\",\"hasPersistentData\":false}" > /dev/null || true

# ─── 6. SET ENVIRONMENT VARIABLES ───────────────────────────────────────────
info "Setting environment variables..."
curl -sf -X POST "${CAPROVER_URL}/api/v2/user/apps/appDefinitions/update" \
  -H "Content-Type: application/json" \
  -H "x-captain-auth: ${TOKEN}" \
  -d "{
    \"appName\": \"${APP_NAME}\",
    \"envVars\": [
      {\"key\":\"APP_DEBUG\", \"value\":\"false\"},
      {\"key\":\"APP_URL\",   \"value\":\"${APP_URL}\"},
      {\"key\":\"DB_HOST\",   \"value\":\"${DB_HOST}\"},
      {\"key\":\"DB_PORT\",   \"value\":\"${DB_PORT}\"},
      {\"key\":\"DB_NAME\",   \"value\":\"${DB_NAME}\"},
      {\"key\":\"DB_USER\",   \"value\":\"${DB_USER}\"},
      {\"key\":\"DB_PASS\",   \"value\":\"${DB_PASS}\"}
    ]
  }" > /dev/null
info "Env vars set."

# ─── 7. ENABLE HTTPS ─────────────────────────────────────────────────────────
info "Enabling HTTPS..."
curl -sf -X POST "${CAPROVER_URL}/api/v2/user/apps/appDefinitions/enablebasedomainssl" \
  -H "Content-Type: application/json" \
  -H "x-captain-auth: ${TOKEN}" \
  -d "{\"appName\":\"${APP_NAME}\"}" > /dev/null \
  || warn "HTTPS may already be enabled."

# ─── 8. DEPLOY ───────────────────────────────────────────────────────────────
info "Deploying to CapRover from current directory..."
caprover deploy \
  --caproverUrl      "$CAPROVER_URL" \
  --caproverPassword "$CAPROVER_PASSWORD" \
  --appName          "$APP_NAME" \
  --branch           "main"

# ─── DONE ────────────────────────────────────────────────────────────────────
info "Deploy complete!"
echo ""
echo "  App URL : ${APP_URL}"
echo "  DB Host : ${DB_HOST}/${DB_NAME}"
echo ""

# ─── CLEANUP ─────────────────────────────────────────────────────────────────
cd /tmp && rm -rf "$DEPLOY_DIR"
info "Temp files cleaned up."
