#!/bin/bash
# Deploy production nginx configuration for XAMXAM
# Fixes permissions and installs /tmp/xamxam.conf into nginx sites-available.
#
# Usage: just deploy-nginx   (uploads script + config, then runs this)
#    or: sudo bash /tmp/deploy-server.sh

set -e

# ── Colors ────────────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

ok()   { printf "${GREEN}✓${NC} %s\n" "$*"; }
err()  { printf "${RED}✗${NC} %s\n" "$*" >&2; }
warn() { printf "${YELLOW}!${NC} %s\n" "$*"; }
# ─────────────────────────────────────────────────────────────────────────────

[ "$EUID" -eq 0 ] || { err "Run as root (sudo)"; exit 1; }

printf "🚀 XAMXAM Production Deployment\n"
printf "================================\n\n"

# ── Step 1: Permissions ───────────────────────────────────────────────────────
printf "📋 Step 1: Fixing file permissions...\n"
echo "--------------------------------------"

chown -R www-data:xamxam /var/www/xamxam/
ok "Ownership: www-data:xamxam"

find /var/www/xamxam -type d -exec chmod 2775 {} \;
ok "Directories: 2775 (setgid)"

find /var/www/xamxam -type f -exec chmod 664 {} \;
ok "Files: 664"

if [ -d "/var/www/xamxam/storage" ]; then
    chmod 2775 /var/www/xamxam/storage
    find /var/www/xamxam/storage -name "*.db" -exec chmod 660 {} \;
    ok "Storage: 2775, databases: 660"
fi

# Migrate posterg.db → xamxam.db if the new name is missing or empty
if [ -f "/var/www/xamxam/storage/posterg.db" ]; then
    if [ ! -s "/var/www/xamxam/storage/xamxam.db" ]; then
        cp /var/www/xamxam/storage/posterg.db /var/www/xamxam/storage/xamxam.db
        ok "Migrated posterg.db → xamxam.db"
    fi
    rm /var/www/xamxam/storage/posterg.db
    ok "Removed legacy posterg.db"
fi

# Ensure writable cache subdirectories exist for php-fpm (www-data)
mkdir -p /var/www/xamxam/storage/cache/rate_limit
chown -R www-data:xamxam /var/www/xamxam/storage/cache
chmod -R 2775 /var/www/xamxam/storage/cache
ok "Cache dirs: created and owned by www-data:xamxam"

# ── Step 1b: htpasswd file ──────────────────────────────────────────────────────
printf "\n📋 Step 1b: Checking htpasswd file...\n"
echo "--------------------------------------"

if [ -f "/etc/nginx/.htpasswd-xamxam" ]; then
    ok "htpasswd file exists: /etc/nginx/.htpasswd-xamxam"
elif [ -f "/etc/nginx/.htpasswd-posterg" ]; then
    cp /etc/nginx/.htpasswd-posterg /etc/nginx/.htpasswd-xamxam
    chmod 644 /etc/nginx/.htpasswd-xamxam
    ok "Migrated .htpasswd-posterg → .htpasswd-xamxam"
else
    warn "No htpasswd file found — admin panel will return 403 until one is created"
    warn "Run: sudo htpasswd -c /etc/nginx/.htpasswd-xamxam <username>"
fi

# ── Step 2: Nginx config ──────────────────────────────────────────────────────
printf "\n📋 Step 2: Deploying nginx configuration...\n"
echo "--------------------------------------------"

if [ ! -f "/tmp/xamxam.conf" ]; then
    err "/tmp/xamxam.conf not found — run: just deploy-nginx"
    exit 1
fi

if [ -f "/etc/nginx/sites-available/xamxam" ]; then
    cp /etc/nginx/sites-available/xamxam \
       "/etc/nginx/sites-available/xamxam.backup.$(date +%Y%m%d_%H%M%S)"
    ok "Backed up existing config"
fi

cp /tmp/xamxam.conf /etc/nginx/sites-available/xamxam
ok "Installed new nginx config"

# Remove legacy posterg symlink if it exists (causes duplicate limit_req_zone)
if [ -L "/etc/nginx/sites-enabled/posterg" ]; then
    rm /etc/nginx/sites-enabled/posterg
    ok "Removed legacy sites-enabled/posterg symlink"
fi

# Remove legacy posterg config and all its backups from sites-available
for f in /etc/nginx/sites-available/posterg /etc/nginx/sites-available/posterg.backup.*; do
    [ -f "$f" ] && rm "$f" && ok "Removed legacy $f"
done

# Keep only the 2 most recent xamxam backups, delete older ones
ls -t /etc/nginx/sites-available/xamxam.backup.* 2>/dev/null | tail -n +3 | xargs -r rm --
ok "Pruned old xamxam config backups (kept 2 most recent)"

if [ ! -L "/etc/nginx/sites-enabled/xamxam" ]; then
    ln -s /etc/nginx/sites-available/xamxam /etc/nginx/sites-enabled/xamxam
    ok "Created sites-enabled symlink"
fi

# ── Step 3: Validate ──────────────────────────────────────────────────────────
printf "\n📋 Step 3: Testing nginx configuration...\n"
echo "------------------------------------------"

if nginx -t 2>&1; then
    ok "Nginx configuration is valid"
else
    err "Nginx configuration has errors — restoring backup"
    latest=$(ls -t /etc/nginx/sites-available/xamxam.backup.* 2>/dev/null | head -1)
    [ -n "$latest" ] && cp "$latest" /etc/nginx/sites-available/xamxam
    exit 1
fi

# ── Step 4: Reload nginx ─────────────────────────────────────────────────────
printf "\n"
echo "📋 Step 4: Reloading nginx..."
echo "------------------------------"

systemctl reload nginx
ok "Nginx reloaded"

# ── Done ──────────────────────────────────────────────────────────────────────
printf "\n"
ok "Permissions fixed"
ok "Nginx config installed"
ok "Configuration validated"
ok "Nginx reloaded"
printf "\nVerify:\n"
printf "  https://xamxam.erg.be/\n"
printf "  https://xamxam.erg.be/admin/\n"
printf "  https://xamxam.erg.be/storage/xamxam.db (should 403/404)\n"
