#!/usr/bin/env bash
# ---------------------------------------------------------------------------
# PlayTube — cPanel one-shot installer (run in the cPanel Terminal / SSH).
#
#   bash scripts/cpanel-install.sh \
#     --db 'postgresql://user:pass@localhost:5432/user_playtube' \
#     --site 'https://tube.example.com' \
#     --admin-email 'admin@example.com' --admin-password 'ChangeMe123!' \
#     --admin-name 'Site Admin' --admin-handle 'admin'
#
# Every flag is optional: missing values are prompted for. Re-running is safe.
# ---------------------------------------------------------------------------
set -euo pipefail

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$APP_DIR"

DB=""; SITE=""; ADMIN_EMAIL=""; ADMIN_PASSWORD=""; ADMIN_NAME="Site Admin"; ADMIN_HANDLE="admin"; YES=0
while [ $# -gt 0 ]; do
  case "$1" in
    --db) DB="$2"; shift 2;;
    --site) SITE="$2"; shift 2;;
    --admin-email) ADMIN_EMAIL="$2"; shift 2;;
    --admin-password) ADMIN_PASSWORD="$2"; shift 2;;
    --admin-name) ADMIN_NAME="$2"; shift 2;;
    --admin-handle) ADMIN_HANDLE="$2"; shift 2;;
    --yes) YES=1; shift;;
    *) echo "Unknown flag: $1"; exit 1;;
  esac
done

need() { command -v "$1" >/dev/null 2>&1 || { echo "Missing required command: $1"; exit 1; }; }
need node; need npm; need npx

echo "▶ Node $(node -v) — app dir: $APP_DIR"
NODE_MAJOR="$(node -p 'Number(process.versions.node.split(".")[0])')"
if [ "$NODE_MAJOR" -lt 20 ]; then echo "Node.js 20+ is required (cPanel → Setup Node.js App → version)."; exit 1; fi

prompt() { # $1 var-name $2 label $3 default $4 secret(0/1)
  local current="${!1:-$3}"
  if [ -n "$current" ]; then printf -v "$1" '%s' "$current"; return; fi
  if [ "$YES" = 1 ]; then echo "Missing required value: $2 (pass --yes with all flags)"; exit 1; fi
  if [ "${4:-0}" = 1 ]; then read -r -s -p "$2: " current; echo; else read -r -p "$2: " current; fi
  printf -v "$1" '%s' "${current:-$3}"
}

prompt DB "DATABASE_URL (postgresql://user:pass@host:5432/db)" "" 0
prompt SITE "SITE_URL (https://...)" "" 0
prompt ADMIN_EMAIL "Admin email" "" 0
prompt ADMIN_PASSWORD "Admin password (min 8 chars)" "" 1
prompt ADMIN_NAME "Admin display name" "Site Admin" 0
prompt ADMIN_HANDLE "Admin handle" "admin" 0

case "$DB" in postgres*://*) ;; *) echo "DATABASE_URL must start with postgresql://"; exit 1;; esac

echo "▶ Installing dependencies…"
npm ci --no-audit --no-fund

if [ ! -f .env ]; then
  echo "▶ Creating .env from .env.example…"
  cp .env.example .env
fi

SECRET="$(node -p 'require("crypto").randomBytes(48).toString("base64")')"
set_env() { # $1 key $2 value
  if grep -qE "^[[:space:]]*$1[[:space:]]*=" .env; then
    perl -i -pe "s{^\\s*$1\\s*=.*}{$1=$2}" .env
  else
    printf '%s=%s\n' "$1" "$2" >> .env
  fi
}
set_env DATABASE_URL "$DB"
set_env SITE_URL "$SITE"
if grep -qE 'change-me|development-secret' .env; then set_env AUTH_SECRET "$SECRET"; fi
export DATABASE_URL="$DB"

echo "▶ Creating database tables…"
npx drizzle-kit push --force

echo "▶ Building production bundle…"
npm run build

echo "▶ Creating admin account…"
node scripts/setup-cli.mjs create-admin --email "$ADMIN_EMAIL" --password "$ADMIN_PASSWORD" \
  --name "$ADMIN_NAME" --handle "$ADMIN_HANDLE" --db "$DB"

echo "▶ Writing install.lock…"
node scripts/setup-cli.mjs lock --site "$SITE"

mkdir -p tmp storage
touch tmp/restart.txt || true

cat <<EOF

✅ PlayTube installed.
   Site : $SITE
   Admin: $ADMIN_EMAIL  (sign in, then open /admin)
   Next : cPanel → Setup Node.js App → Restart (Passenger also watches tmp/restart.txt)
   Demo content (optional): open $SITE/setup and run step 5, or wait for /api/health auto-seed.
EOF
