#!/bin/bash
# ══════════════════════════════════════════════════════════════════════
# SUDANNA AI OS v23 — COMPLETE ACTIVATION SCRIPT
# Run ONCE after uploading package
# Usage: bash cron_setup.sh
# ══════════════════════════════════════════════════════════════════════

set -e  # stop on any error

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║   Sudanna AI OS v23 — Server Activation                    ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

# ── Detect PHP binary ────────────────────────────────────────────────
PHP=""
for candidate in php php8.2 php8.1 /usr/local/bin/php /usr/bin/php; do
  if command -v "$candidate" &>/dev/null; then
    PHP=$(command -v "$candidate")
    break
  fi
done
if [ -z "$PHP" ]; then
  echo "❌ ERROR: PHP not found. Set path manually."
  exit 1
fi
echo "✅ PHP: $PHP ($(${PHP} -r 'echo PHP_VERSION;'))"

# ── Paths ────────────────────────────────────────────────────────────
ROOT="/home/saiadmin/public_html/s26"
LOG="/home/saiadmin/logs"

echo "✅ Root: $ROOT"
echo "✅ Logs: $LOG"

# ── FIX: Create logs directory AND all log files upfront ─────────────
# This fixes: jailshell: No such file or directory
mkdir -p "$LOG"
for logfile in worker kpi expire reconcile settle cache booking error; do
  touch "$LOG/${logfile}.log"
  chmod 664 "$LOG/${logfile}.log"
done
echo "✅ Log files created and ready:"
ls -la "$LOG"/*.log 2>/dev/null | awk '{print "   "$NF}'

# ── Set permissions ──────────────────────────────────────────────────
chmod 755 "$ROOT/cron/"*.php 2>/dev/null || true
chmod 600 "$ROOT/.env"       2>/dev/null || true
chmod 755 "$ROOT/uploads"    2>/dev/null || true
echo "✅ Permissions set"

# ── PHP test ──────────────────────────────────────────────────────────
echo ""
echo "=== PHP connectivity test ==="
$PHP -r "echo 'PHP OK: '.PHP_VERSION.PHP_EOL;" || { echo "❌ PHP error"; exit 1; }

# ── Build cron jobs ──────────────────────────────────────────────────
echo ""
echo "=== Installing Cron Jobs ==="

# Remove old Sudanna cron entries, then add fresh set
(crontab -l 2>/dev/null | grep -v "s26/cron" | grep -v "saiadmin.*sudanna") | crontab - 2>/dev/null || true

# Add all 7 cron jobs (ONE entry per line, ONE redirect each)
CRON_JOBS=""
CRON_JOBS="${CRON_JOBS}* * * * * $PHP $ROOT/cron/worker.php >> $LOG/worker.log 2>&1\n"
CRON_JOBS="${CRON_JOBS}0 * * * * $PHP $ROOT/cron/kpi_aggregate.php >> $LOG/kpi.log 2>&1\n"
CRON_JOBS="${CRON_JOBS}0 2 * * * $PHP $ROOT/cron/booking_cleanup.php >> $LOG/booking.log 2>&1\n"
CRON_JOBS="${CRON_JOBS}0 3 * * * $PHP $ROOT/cron/cache_cleanup.php >> $LOG/cache.log 2>&1\n"
CRON_JOBS="${CRON_JOBS}0 */6 * * * $PHP $ROOT/cron/expire_invoices.php >> $LOG/expire.log 2>&1\n"
CRON_JOBS="${CRON_JOBS}30 2 * * * $PHP $ROOT/cron/reconcile.php >> $LOG/reconcile.log 2>&1\n"
CRON_JOBS="${CRON_JOBS}0 3 * * * $PHP $ROOT/cron/settle.php >> $LOG/settle.log 2>&1\n"

# Install
(crontab -l 2>/dev/null; printf "$CRON_JOBS") | crontab -

echo "✅ Cron jobs installed:"
crontab -l | grep "s26/cron" | while read line; do echo "   $line"; done

# ── Verify worker can run ────────────────────────────────────────────
echo ""
echo "=== Worker dry-run test ==="
cd "$ROOT" && $PHP -l cron/worker.php && echo "✅ worker.php syntax OK" || echo "❌ worker.php has errors"

# ── Final summary ────────────────────────────────────────────────────
echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║   ACTIVATION COMPLETE                                       ║"
echo "╠══════════════════════════════════════════════════════════════╣"
echo "║  ✅ Log directory + 8 log files created                     ║"
echo "║  ✅ 7 cron jobs installed                                    ║"
echo "║  ✅ File permissions set                                     ║"
echo "╠══════════════════════════════════════════════════════════════╣"
echo "║  NEXT STEPS:                                                ║"
echo "║  1. phpMyAdmin → Import sudanna_v22_schema_complete.sql     ║"
echo "║  2. phpMyAdmin → SQL → Run activation.sql                   ║"
echo "║  3. Edit .env with real API keys                            ║"
echo "║  4. Open: /go_live_proof.php?token=GOLIVE2026           ║"
echo "║  5. Confirm 18/18 passed                                    ║"
echo "║  6. Delete go_live_proof.php immediately after              ║"
echo "╚══════════════════════════════════════════════════════════════╝"
