#!/bin/bash
# ═══════════════════════════════════════════════════════
# CFD Portal FTP Deploy Script
# Usage: ./deploy/ftp-sync.sh [--dry-run]
#
# Add to ~/.zshrc:
# alias cfd-deploy='cd ~/Responise\ IQ\ Web\ Apps/responseiq.ai/cincinnatifire && ./deploy/ftp-sync.sh'
# ═══════════════════════════════════════════════════════

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LOCAL_PATH="$(dirname "$SCRIPT_DIR")"

# Load .env
if [ ! -f "$LOCAL_PATH/.env" ]; then
    echo "ERROR: .env file not found at $LOCAL_PATH/.env"
    exit 1
fi

# Parse .env variables manually to handle special chars
FTP_HOST=$(grep '^FTP_HOST=' "$LOCAL_PATH/.env" | cut -d'=' -f2-)
FTP_USER=$(grep '^FTP_USER=' "$LOCAL_PATH/.env" | cut -d'=' -f2-)
FTP_PASS=$(grep '^FTP_PASS=' "$LOCAL_PATH/.env" | cut -d'=' -f2-)
FTP_REMOTE_PATH=$(grep '^FTP_REMOTE_PATH=' "$LOCAL_PATH/.env" | cut -d'=' -f2-)

echo "======================================"
echo "  CFD Portal Deploy — $(date '+%Y-%m-%d %H:%M:%S')"
echo "======================================"
echo "Local:  $LOCAL_PATH"
echo "Remote: $FTP_USER@$FTP_HOST:$FTP_REMOTE_PATH"
echo ""

# Check for dry run
DRY=""
if [ "$1" = "--dry-run" ]; then
    echo "*** DRY RUN MODE — no files will be transferred ***"
    echo ""
    DRY="--dry-run"
fi

lftp <<EOF
set ssl:verify-certificate no
set net:timeout 30
set net:max-retries 3
open $FTP_HOST
user "$FTP_USER" "$FTP_PASS"
lcd "$LOCAL_PATH"
cd "$FTP_REMOTE_PATH"
mirror --reverse --delete --verbose --only-newer --parallel=4 $DRY \
  --exclude .env \
  --exclude .git/ \
  --exclude .gitignore \
  --exclude deploy/ \
  --exclude .DS_Store \
  --exclude-glob *.log \
  --exclude node_modules/ \
  --exclude uploads/overtime/ \
  ./ ./
bye
EOF

echo ""
echo "Deploy complete!"
echo ""

# ─── Post-deploy health check ───────────────────────────
APP_URL=$(grep '^APP_URL=' "$LOCAL_PATH/.env" | cut -d'=' -f2-)
APP_URL="${APP_URL:-https://cincinnatifire.ai}"

echo "Running post-deploy health checks..."
echo ""

FAIL=0

# Check main pages for 500 errors
PAGES=("/" "/index.php" "/register.php")
for PAGE in "${PAGES[@]}"; do
    STATUS=$(curl -sk -o /dev/null -w "%{http_code}" "${APP_URL}${PAGE}" 2>/dev/null)
    if [ "$STATUS" = "500" ] || [ "$STATUS" = "503" ]; then
        echo "  FAIL  ${PAGE} → HTTP $STATUS"
        FAIL=1
    elif [ "$STATUS" = "000" ]; then
        echo "  WARN  ${PAGE} → No response (DNS/SSL issue?)"
    else
        echo "  OK    ${PAGE} → HTTP $STATUS"
    fi
done

# Check for error_log on remote
echo ""
echo "Checking remote error_log..."
ERROR_LOG=$(lftp -e "set ssl:verify-certificate no; open $FTP_HOST; user \"$FTP_USER\" \"$FTP_PASS\"; cat error_log 2>/dev/null; bye" 2>/dev/null | tail -5)
if [ -n "$ERROR_LOG" ]; then
    echo "  WARNING: Errors found on server:"
    echo "$ERROR_LOG" | while read -r line; do echo "    $line"; done
else
    echo "  OK    No errors in error_log"
fi

echo ""
if [ "$FAIL" -eq 1 ]; then
    echo "*** HEALTH CHECK FAILED — 500 errors detected! ***"
    echo "Check the remote error_log or run:"
    echo "  lftp -e \"set ssl:verify-certificate no; open $FTP_HOST; user \\\"$FTP_USER\\\" \\\"$FTP_PASS\\\"; cat error_log; bye\""
    exit 1
else
    echo "All checks passed!"
fi
echo "Site: $APP_URL"
