#!/bin/bash

################################################################################
# Fogbreak Server Setup Script — Ubuntu 24.04 LTS on Hetzner Cloud VPS
################################################################################
#
# Purpose: Complete production-grade setup for Fogbreak migration from Bluehost
# to Hetzner Cloud. Single-run idempotent installation of all dependencies,
# configuration, and application setup.
#
# Usage: sudo bash setup-server.sh \
#   --domain=fogbreak.io \
#   --github-repo=fogbreak-io/fogbreak \
#   --github-token=ghp_xxxxx \
#   --db-password=secure_password \
#   --db-dump=/path/to/dump.sql
#
# Author: Fogbreak Build System
# Last Updated: March 29, 2026
#
################################################################################

set -euo pipefail

# ============================================================================
# COLOR OUTPUT
# ============================================================================

readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly NC='\033[0m'  # No Color

log_info() {
    echo -e "${BLUE}[INFO]${NC} $*"
}

log_success() {
    echo -e "${GREEN}[✓]${NC} $*"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $*"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $*"
    exit 1
}

# ============================================================================
# CONFIGURATION & DEFAULTS
# ============================================================================

DOMAIN="${DOMAIN:-fogbreak.io}"
GITHUB_REPO="${GITHUB_REPO:-fogbreak-io/fogbreak}"
GITHUB_TOKEN="${GITHUB_TOKEN:-}"
DB_PASSWORD="${DB_PASSWORD:-}"
DB_DUMP="${DB_DUMP:-}"
APP_DIR="/var/www/fogbreak.io"
DEPLOY_USER="fogbreak"
DEPLOY_HOME="/home/${DEPLOY_USER}"

# Parse command-line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --domain=*)
            DOMAIN="${1#*=}"
            shift
            ;;
        --github-repo=*)
            GITHUB_REPO="${1#*=}"
            shift
            ;;
        --github-token=*)
            GITHUB_TOKEN="${1#*=}"
            shift
            ;;
        --db-password=*)
            DB_PASSWORD="${1#*=}"
            shift
            ;;
        --db-dump=*)
            DB_DUMP="${1#*=}"
            shift
            ;;
        *)
            log_error "Unknown option: $1"
            ;;
    esac
done

# Validate critical inputs
if [[ -z "$DB_PASSWORD" ]]; then
    log_error "Database password required: --db-password=XXXX"
fi

# ============================================================================
# PRE-FLIGHT CHECKS
# ============================================================================

log_info "Running pre-flight checks..."

if [[ $EUID -ne 0 ]]; then
    log_error "This script must be run as root (use: sudo)"
fi

if ! command -v lsb_release &> /dev/null; then
    log_error "lsb_release not found. This script requires Ubuntu 24.04."
fi

OS_VERSION=$(lsb_release -rs)
if [[ "$OS_VERSION" != "24.04" ]]; then
    log_warn "This script is tested on Ubuntu 24.04. Current: $OS_VERSION. Continuing anyway..."
fi

log_success "Pre-flight checks passed"

# ============================================================================
# SYSTEM UPDATES
# ============================================================================

log_info "Updating system packages..."
apt-get update
apt-get upgrade -y
apt-get install -y \
    curl wget git htop vim nano ufw fail2ban unattended-upgrades \
    build-essential software-properties-common apt-transport-https \
    ca-certificates gnupg lsb-release

log_success "System packages updated"

# ============================================================================
# SECURITY: UFW FIREWALL
# ============================================================================

log_info "Configuring UFW firewall..."

if ! ufw status | grep -q "Status: active"; then
    ufw --force enable
    log_success "UFW enabled"
else
    log_warn "UFW already enabled"
fi

# Allow SSH, HTTP, HTTPS
ufw allow 22/tcp comment "SSH"
ufw allow 80/tcp comment "HTTP"
ufw allow 443/tcp comment "HTTPS"
# Deny everything else by default (already set to deny incoming)

log_success "Firewall rules configured"

# ============================================================================
# SECURITY: fail2ban
# ============================================================================

log_info "Configuring fail2ban..."

systemctl enable fail2ban
systemctl restart fail2ban

log_success "fail2ban enabled"

# ============================================================================
# SECURITY: Automatic Updates
# ============================================================================

log_info "Enabling automatic security updates..."

apt-get install -y unattended-upgrades

cat > /etc/apt/apt.conf.d/50unattended-upgrades << 'EOF'
Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}-security";
};
Unattended-Upgrade::Package-Blacklist {
};
Unattended-Upgrade::DevRelease "false";
EOF

systemctl enable unattended-upgrades
systemctl restart unattended-upgrades

log_success "Automatic security updates enabled"

# ============================================================================
# DEPLOY USER & SSH SETUP
# ============================================================================

log_info "Setting up deploy user: ${DEPLOY_USER}"

if ! id -u "$DEPLOY_USER" &>/dev/null; then
    useradd -m -s /bin/bash "$DEPLOY_USER"
    usermod -aG sudo "$DEPLOY_USER"
    log_success "Deploy user created: $DEPLOY_USER"
else
    log_warn "Deploy user already exists: $DEPLOY_USER"
fi

# Create SSH directory if it doesn't exist
mkdir -p "${DEPLOY_HOME}/.ssh"
chmod 700 "${DEPLOY_HOME}/.ssh"
chown -R "${DEPLOY_USER}:${DEPLOY_USER}" "${DEPLOY_HOME}/.ssh"

log_success "Deploy user configured"

# ============================================================================
# PHP 8.3 + FPM
# ============================================================================

log_info "Installing PHP 8.3..."

if ! command -v php &> /dev/null; then
    add-apt-repository ppa:ondrej/php -y
    apt-get update

    apt-get install -y \
        php8.3-fpm php8.3-cli php8.3-dev \
        php8.3-pdo php8.3-mysql php8.3-pgsql \
        php8.3-mbstring php8.3-curl php8.3-xml php8.3-zip \
        php8.3-gd php8.3-imagick php8.3-intl \
        php8.3-opcache php8.3-redis \
        php8.3-bcmath php8.3-json

    log_success "PHP 8.3 installed"
else
    log_warn "PHP already installed: $(php -v | head -1)"
fi

# Configure PHP-FPM pool for Fogbreak
log_info "Configuring PHP-FPM pool for Fogbreak..."

cat > /etc/php/8.3/fpm/pool.d/fogbreak.conf << 'EOF'
[fogbreak]
user = www-data
group = www-data
listen = /run/php/php8.3-fogbreak.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.process_idle_timeout = 30s

catch_workers_output = yes
clear_env = no

; Security & performance
php_admin_value[memory_limit] = 256M
php_admin_value[max_execution_time] = 300
php_admin_value[max_input_time] = 60
php_admin_value[upload_max_filesize] = 100M
php_admin_value[post_max_size] = 100M
php_admin_value[display_errors] = Off
php_admin_value[log_errors] = On
php_admin_value[error_log] = /var/log/php/fogbreak-error.log
EOF

mkdir -p /var/log/php
chmod 755 /var/log/php

systemctl restart php8.3-fpm
log_success "PHP-FPM configured"

# ============================================================================
# NGINX
# ============================================================================

log_info "Installing Nginx..."

if ! command -v nginx &> /dev/null; then
    apt-get install -y nginx
    log_success "Nginx installed"
else
    log_warn "Nginx already installed"
fi

# Remove default site
rm -f /etc/nginx/sites-enabled/default

log_success "Nginx installed"

# ============================================================================
# MYSQL 8.0
# ============================================================================

log_info "Installing MySQL 8.0..."

if ! command -v mysql &> /dev/null; then
    apt-get install -y mysql-server mysql-client

    # Secure MySQL installation (automated)
    mysql -e "FLUSH PRIVILEGES;"
    mysql -e "UPDATE mysql.user SET authentication_string=PASSWORD('root') WHERE user='root' AND host='localhost';"
    mysql -e "DROP USER IF EXISTS ''@'localhost';"
    mysql -e "DROP USER IF EXISTS ''@'$(hostname)';"
    mysql -e "DROP DATABASE IF EXISTS test;"
    mysql -e "FLUSH PRIVILEGES;"

    log_success "MySQL 8.0 installed and secured"
else
    log_warn "MySQL already installed"
fi

systemctl enable mysql
systemctl restart mysql

log_success "MySQL configured"

# ============================================================================
# POSTGRESQL 16 (for future migration per instruction 02)
# ============================================================================

log_info "Installing PostgreSQL 16..."

if ! command -v psql &> /dev/null; then
    sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
    wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -
    apt-get update
    apt-get install -y postgresql-16 postgresql-contrib-16

    log_success "PostgreSQL 16 installed"
else
    log_warn "PostgreSQL already installed"
fi

systemctl enable postgresql
systemctl restart postgresql

log_success "PostgreSQL configured"

# ============================================================================
# REDIS
# ============================================================================

log_info "Installing Redis..."

if ! command -v redis-cli &> /dev/null; then
    apt-get install -y redis-server

    # Configure Redis for caching & sessions
    sed -i 's/^# maxmemory <bytes>/maxmemory 512mb/' /etc/redis/redis.conf
    sed -i 's/^# maxmemory-policy noeviction/maxmemory-policy allkeys-lru/' /etc/redis/redis.conf

    log_success "Redis installed"
else
    log_warn "Redis already installed"
fi

systemctl enable redis-server
systemctl restart redis-server

log_success "Redis configured"

# ============================================================================
# NODE.JS 22 LTS (for Next.js frontend, instruction 15)
# ============================================================================

log_info "Installing Node.js 22 LTS..."

if ! command -v node &> /dev/null; then
    curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
    apt-get install -y nodejs

    npm install -g npm@latest
    npm install -g pm2

    log_success "Node.js 22 LTS and npm installed"
else
    log_warn "Node.js already installed: $(node -v)"
fi

log_success "Node.js configured"

# ============================================================================
# COMPOSER (PHP Package Manager)
# ============================================================================

log_info "Installing Composer..."

if ! command -v composer &> /dev/null; then
    curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
    log_success "Composer installed"
else
    log_warn "Composer already installed"
fi

# ============================================================================
# CERTBOT (Let's Encrypt SSL)
# ============================================================================

log_info "Installing Certbot for SSL certificates..."

if ! command -v certbot &> /dev/null; then
    apt-get install -y certbot python3-certbot-nginx
    log_success "Certbot installed"
else
    log_warn "Certbot already installed"
fi

# ============================================================================
# OLLAMA (AI inference — install, don't start models yet)
# ============================================================================

log_info "Installing Ollama for AI inference..."

if ! command -v ollama &> /dev/null; then
    curl -fsSL https://ollama.ai/install.sh | sh || log_warn "Ollama installation failed, continuing..."

    # Create ollama service user
    useradd -r -s /bin/false ollama 2>/dev/null || true

    # Configure systemd service
    systemctl enable ollama || true
    systemctl restart ollama || true

    log_success "Ollama installed (models will be pulled separately)"
else
    log_warn "Ollama already installed"
fi

# ============================================================================
# PYTHON 3.12 + venv (for FastAPI AI proxy)
# ============================================================================

log_info "Installing Python 3.12..."

if ! command -v python3.12 &> /dev/null; then
    apt-get install -y python3.12 python3.12-venv python3.12-dev python3-pip
    log_success "Python 3.12 installed"
else
    log_warn "Python 3.12 already installed"
fi

# ============================================================================
# APPLICATION DIRECTORY SETUP
# ============================================================================

log_info "Setting up application directory: ${APP_DIR}"

if [[ ! -d "$APP_DIR" ]]; then
    mkdir -p "$APP_DIR"
    log_success "Application directory created"
else
    log_warn "Application directory already exists"
fi

chmod 755 "$APP_DIR"
chown -R www-data:www-data "$APP_DIR"

# ============================================================================
# GIT SETUP & REPOSITORY CLONE
# ============================================================================

log_info "Cloning Fogbreak repository..."

if [[ ! -d "${APP_DIR}/.git" ]]; then
    cd "$APP_DIR" || exit 1

    if [[ -n "$GITHUB_TOKEN" ]]; then
        git clone "https://${GITHUB_TOKEN}@github.com/${GITHUB_REPO}.git" .
    else
        git clone "https://github.com/${GITHUB_REPO}.git" .
        log_warn "GitHub token not provided. Repository cloned but future pulls may fail if private."
    fi

    git config user.email "deploy@${DOMAIN}"
    git config user.name "Fogbreak Deploy"

    log_success "Repository cloned"
else
    log_warn "Repository already exists at ${APP_DIR}"
    cd "$APP_DIR" || exit 1
    git fetch origin
fi

# ============================================================================
# DATABASE SETUP
# ============================================================================

log_info "Setting up MySQL databases..."

# Create Fogbreak database and user
mysql -e "
CREATE DATABASE IF NOT EXISTS fogbreak CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'fogbreak_app'@'localhost' IDENTIFIED BY '${DB_PASSWORD}';
GRANT ALL PRIVILEGES ON fogbreak.* TO 'fogbreak_app'@'localhost';
FLUSH PRIVILEGES;
"

log_success "MySQL database and user created"

# Import database dump if provided
if [[ -n "$DB_DUMP" && -f "$DB_DUMP" ]]; then
    log_info "Importing database from: $DB_DUMP"
    mysql fogbreak < "$DB_DUMP"
    log_success "Database import complete"
elif [[ -n "$DB_DUMP" ]]; then
    log_error "Database dump file not found: $DB_DUMP"
else
    log_warn "No database dump provided. Import later with: mysql fogbreak < dump.sql"
fi

# ============================================================================
# FOGBREAK CONFIG.PHP
# ============================================================================

log_info "Generating config.php from template..."

if [[ -f "${APP_DIR}/api/config.php.example" ]]; then
    cp "${APP_DIR}/api/config.php.example" "${APP_DIR}/api/config.php"

    # Replace placeholders (these should match config.php.example format)
    sed -i "s|DB_HOST|localhost|g" "${APP_DIR}/api/config.php"
    sed -i "s|DB_NAME|fogbreak|g" "${APP_DIR}/api/config.php"
    sed -i "s|DB_USER|fogbreak_app|g" "${APP_DIR}/api/config.php"
    sed -i "s|DB_PASS|${DB_PASSWORD}|g" "${APP_DIR}/api/config.php"
    sed -i "s|DOMAIN|${DOMAIN}|g" "${APP_DIR}/api/config.php"

    chmod 640 "${APP_DIR}/api/config.php"
    chown www-data:www-data "${APP_DIR}/api/config.php"

    log_success "config.php generated"
else
    log_warn "config.php.example not found. Manual setup required."
fi

# ============================================================================
# .ENV FILE TEMPLATE
# ============================================================================

log_info "Creating .env template..."

cat > "${APP_DIR}/.env.example" << 'ENVEOF'
# Fogbreak Environment Configuration

# Database
DB_HOST=localhost
DB_PORT=3306
DB_NAME=fogbreak
DB_USER=fogbreak_app
DB_PASS=change_me_in_production

# Application
DOMAIN=fogbreak.io
APP_ENV=production
APP_DEBUG=false

# Email (cPanel SMTP or external)
MAIL_HOST=mail.fogbreak.io
MAIL_PORT=465
MAIL_ENCRYPTION=ssl
MAIL_USERNAME=noreply@fogbreak.io
MAIL_PASSWORD=change_me

# Gmail IMAP (for inbox sync)
GMAIL_USER=fogbreak@gmail.com
GMAIL_PASS=app_password_from_google

# GitHub Deploy
GITHUB_TOKEN=change_me
GITHUB_WEBHOOK_SECRET=change_me

# AI / Ollama
OLLAMA_API_URL=http://localhost:11434
OLLAMA_MODEL_REASONING=llama2-70b
OLLAMA_MODEL_CHAT=mistral-7b

# FastAPI AI Proxy
FASTAPI_URL=http://localhost:8000
FASTAPI_SECRET=change_me

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0

# Cron / Automation
CRON_API_KEY=MTH_PORTAL_2026
CRON_SECRET=change_me

# API Keys (third-party integrations — leave blank initially)
GOOGLE_OAUTH_CLIENT_ID=
GOOGLE_OAUTH_SECRET=
COLLOV_API_KEY=
RUNWAY_API_KEY=
ELEVENLABS_API_KEY=
TWILIO_ACCOUNT_SID=
TWILIO_AUTH_TOKEN=
TWILIO_PHONE=
META_API_TOKEN=
GOOGLE_ADS_API_KEY=
TIKTOK_API_KEY=
LINKEDIN_API_KEY=

# Logging
LOG_LEVEL=info
LOG_FILE=/var/log/fogbreak/app.log

ENVEOF

chmod 640 "${APP_DIR}/.env.example"
chown www-data:www-data "${APP_DIR}/.env.example"

log_success ".env template created at ${APP_DIR}/.env.example"

# ============================================================================
# NGINX CONFIGURATION
# ============================================================================

log_info "Configuring Nginx for ${DOMAIN}..."

cat > "/etc/nginx/sites-available/${DOMAIN}" << 'NGINXEOF'
# Fogbreak Nginx Configuration
# SSL will be added by Certbot

upstream php_backend {
    server unix:/run/php/php8.3-fogbreak.sock;
}

upstream next_frontend {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name DOMAIN_PLACEHOLDER;
    root /var/www/DOMAIN_PLACEHOLDER;
    index fogbreak.html;

    # Logging
    access_log /var/log/nginx/fogbreak-access.log combined;
    error_log /var/log/nginx/fogbreak-error.log warn;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript
               application/json application/javascript application/xml+rss
               application/rss+xml application/atom+xml image/svg+xml
               text/x-js text/x-component text/x-cross-domain-policy;

    # Static files (aggressive caching)
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        log_not_found off;
    }

    # API routes → PHP-FPM
    location ~ ^/api/.*\.php$ {
        try_files $uri =404;
        fastcgi_pass php_backend;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_buffer_size 32k;
        fastcgi_buffers 8 32k;
        fastcgi_busy_buffers_size 64k;
    }

    # HTML files (SPA)
    location ~ \.html$ {
        try_files $uri =404;
        add_header Cache-Control "max-age=3600, must-revalidate";
    }

    # Service Worker
    location = /sw.js {
        add_header Cache-Control "max-age=0, no-cache, no-store, must-revalidate";
        add_header Service-Worker-Allowed "/";
    }

    # Next.js frontend (instruction 15 — reverse proxy)
    location /next/ {
        proxy_pass http://next_frontend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
    }

    # Deny access to sensitive files
    location ~ /\. {
        deny all;
        log_not_found off;
    }

    location ~ ~$ {
        deny all;
        log_not_found off;
    }

    location ~ ^/(config\.php|\.env|\.git) {
        deny all;
    }

    # Default: try file, then directory, then rewrite to SPA
    location / {
        try_files $uri $uri/ /fogbreak.html;
    }
}
NGINXEOF

# Replace domain placeholder
sed -i "s|DOMAIN_PLACEHOLDER|${DOMAIN}|g" "/etc/nginx/sites-available/${DOMAIN}"

# Enable site
ln -sf "/etc/nginx/sites-available/${DOMAIN}" "/etc/nginx/sites-enabled/${DOMAIN}"

# Test Nginx config
if nginx -t; then
    systemctl restart nginx
    log_success "Nginx configured and restarted"
else
    log_error "Nginx configuration test failed"
fi

# ============================================================================
# CERTBOT SSL CERTIFICATE
# ============================================================================

log_info "Setting up SSL certificate with Certbot..."

if [[ ! -d "/etc/letsencrypt/live/${DOMAIN}" ]]; then
    # Certbot needs HTTP to be reachable for ACME challenge
    certbot certonly --nginx --non-interactive --agree-tos \
        --email "admin@${DOMAIN}" \
        -d "${DOMAIN}" \
        -d "www.${DOMAIN}" 2>&1 || log_warn "Certbot failed. Ensure domain DNS is pointing to this IP."

    log_success "SSL certificate installed"
else
    log_warn "SSL certificate already exists for ${DOMAIN}"
fi

# Auto-renewal
systemctl enable certbot.timer
systemctl restart certbot.timer

log_success "SSL auto-renewal configured"

# ============================================================================
# CRON JOBS (every 15 minutes)
# ============================================================================

log_info "Configuring Fogbreak cron jobs..."

cat > /etc/cron.d/fogbreak-cron << 'CRONEOF'
# Fogbreak scheduled tasks - every 15 minutes
# Runs /api/cron.php with API key authentication

*/15 * * * * www-data curl -s -X POST \
  -H "Authorization: Bearer MTH_PORTAL_2026" \
  -H "X-Cron-Secret: $(grep 'CRON_SECRET' /var/www/DOMAIN_PLACEHOLDER/.env 2>/dev/null || echo '')" \
  "http://localhost/api/cron.php" >> /var/log/fogbreak/cron.log 2>&1

CRONEOF

sed -i "s|DOMAIN_PLACEHOLDER|${DOMAIN}|g" /etc/cron.d/fogbreak-cron
chmod 644 /etc/cron.d/fogbreak-cron

log_success "Cron jobs configured"

# ============================================================================
# LOGGING & LOG ROTATION
# ============================================================================

log_info "Setting up logging and rotation..."

mkdir -p /var/log/fogbreak
chmod 755 /var/log/fogbreak
chown www-data:www-data /var/log/fogbreak

cat > /etc/logrotate.d/fogbreak << 'LOGROTEOF'
/var/log/fogbreak/*.log {
    daily
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data www-data
    sharedscripts
    postrotate
        systemctl reload nginx > /dev/null 2>&1 || true
    endscript
}
LOGROTEOF

log_success "Logging configured with rotation"

# ============================================================================
# GITHUB WEBHOOK RECEIVER (auto-deploy on push)
# ============================================================================

log_info "Setting up GitHub webhook receiver for auto-deployment..."

mkdir -p "${APP_DIR}/deploy"
chmod 755 "${APP_DIR}/deploy"

cat > "${APP_DIR}/deploy/webhook.php" << 'WEBHOOKEOF'
<?php
/**
 * GitHub Webhook Receiver
 *
 * Validates webhook signature and pulls latest code from main branch.
 * Add this URL to GitHub webhook settings:
 *   Payload URL: https://fogbreak.io/deploy/webhook.php
 *   Content Type: application/json
 *   Secret: (set GITHUB_WEBHOOK_SECRET in .env)
 *   Events: Push
 */

$CONFIG_FILE = '/var/www/DOMAIN_PLACEHOLDER/api/config.php';
$WEBHOOK_LOG = '/var/log/fogbreak/webhook.log';

// Load config
if (!file_exists($CONFIG_FILE)) {
    http_response_code(500);
    die('Config not found');
}
require $CONFIG_FILE;

// Get webhook signature
$signature = $_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? '';
$payload = file_get_contents('php://input');

// Validate signature (HMAC-SHA256)
$secret = getenv('GITHUB_WEBHOOK_SECRET') ?: 'default-secret-change-me';
$hash = 'sha256=' . hash_hmac('sha256', $payload, $secret);

if (!hash_equals($hash, $signature)) {
    logWebhook('Invalid signature');
    http_response_code(403);
    die('Forbidden');
}

$data = json_decode($payload, true);

// Only deploy on pushes to main
if ($data['ref'] !== 'refs/heads/main') {
    logWebhook('Ignoring non-main branch push');
    http_response_code(200);
    die('OK - ignoring branch');
}

// Pull latest code
$output = shell_exec('cd /var/www/DOMAIN_PLACEHOLDER && git pull origin main 2>&1');
logWebhook("Deploy triggered: " . trim($output));

// Clear opcache
if (function_exists('opcache_reset')) {
    opcache_reset();
    logWebhook('OPcache cleared');
}

http_response_code(200);
echo json_encode(['status' => 'deployed', 'time' => date('Y-m-d H:i:s')]);

function logWebhook($message) {
    global $WEBHOOK_LOG;
    file_put_contents($WEBHOOK_LOG, "[" . date('Y-m-d H:i:s') . "] " . $message . "\n", FILE_APPEND);
}
WEBHOOKEOF

sed -i "s|DOMAIN_PLACEHOLDER|${DOMAIN}|g" "${APP_DIR}/deploy/webhook.php"
chmod 644 "${APP_DIR}/deploy/webhook.php"
chown www-data:www-data "${APP_DIR}/deploy/webhook.php"

log_success "GitHub webhook receiver installed"

# ============================================================================
# SYSTEMD SERVICES (for AI components — future)
# ============================================================================

log_info "Creating systemd service templates..."

# FastAPI AI Proxy service (will be enabled in instruction 03)
cat > /etc/systemd/system/fogbreak-ai-proxy.service << 'SERVICEEOF'
[Unit]
Description=Fogbreak AI Proxy (FastAPI)
After=network.target
Wants=fogbreak-ai-proxy.service

[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/DOMAIN_PLACEHOLDER
Environment="PATH=/var/www/DOMAIN_PLACEHOLDER/venv/bin"
ExecStart=/var/www/DOMAIN_PLACEHOLDER/venv/bin/python3 /var/www/DOMAIN_PLACEHOLDER/ai/proxy.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
SERVICEEOF

sed -i "s|DOMAIN_PLACEHOLDER|${DOMAIN}|g" /etc/systemd/system/fogbreak-ai-proxy.service
systemctl daemon-reload

log_success "AI Proxy service template created"

# ============================================================================
# FINAL VERIFICATION
# ============================================================================

log_info "Running final verification checks..."

# Check all critical services
SERVICES=("nginx" "php8.3-fpm" "mysql" "postgresql" "redis-server" "fail2ban")
for service in "${SERVICES[@]}"; do
    if systemctl is-active --quiet "$service"; then
        log_success "$service running"
    else
        log_warn "$service not running"
    fi
done

# Test PHP-FPM
if php -v &>/dev/null; then
    log_success "PHP executable working: $(php -v | head -1)"
fi

# Test MySQL connection
if mysql -u fogbreak_app -p"${DB_PASSWORD}" -e "SELECT 1;" &>/dev/null; then
    log_success "MySQL connection verified"
else
    log_warn "MySQL connection test failed (may be normal if fresh install)"
fi

# Test Nginx config
if nginx -t 2>&1 | grep -q "successful"; then
    log_success "Nginx configuration valid"
fi

# ============================================================================
# SUMMARY & NEXT STEPS
# ============================================================================

cat << EOF

${GREEN}================================================================================
                    FOGBREAK SERVER SETUP COMPLETE
================================================================================${NC}

${GREEN}✓ Installation Summary${NC}
  - Operating System: Ubuntu 24.04 LTS
  - PHP 8.3 (FPM)
  - MySQL 8.0 (database: fogbreak)
  - PostgreSQL 16 (ready for migration per instruction 02)
  - Nginx (reverse proxy, SSL ready)
  - Redis (caching/sessions)
  - Node.js 22 LTS (Next.js frontend)
  - Certbot (Let's Encrypt SSL)
  - Ollama (local AI inference)
  - Python 3.12 (FastAPI AI proxy)
  - Composer (PHP packages)
  - Security: UFW, fail2ban, auto-updates

${GREEN}✓ Application Setup${NC}
  - Repository: ${APP_DIR}
  - Domain: ${DOMAIN}
  - Database: fogbreak / fogbreak_app
  - Config: ${APP_DIR}/api/config.php
  - Nginx config: /etc/nginx/sites-available/${DOMAIN}
  - Cron: every 15 min via /api/cron.php
  - Logging: /var/log/fogbreak/

${GREEN}✓ Security${NC}
  - UFW firewall active (SSH, HTTP, HTTPS only)
  - fail2ban enabled (SSH brute force protection)
  - Automatic security updates enabled
  - SSL certificate requested (if domain DNS resolved)
  - PHP-FPM running as www-data with restricted permissions

${GREEN}✓ GitHub Integration${NC}
  - Auto-deploy webhook at: https://${DOMAIN}/deploy/webhook.php
  - Webhook receiver validates HMAC-SHA256 signatures
  - Pulls main branch on push events

${YELLOW}⚠ NEXT STEPS (In Order)${NC}

1. ${BLUE}Verify SSL Certificate${NC}
   Check: ls -la /etc/letsencrypt/live/${DOMAIN}/
   If missing, run manually:
   $ sudo certbot certonly --nginx -d ${DOMAIN} -d www.${DOMAIN}

2. ${BLUE}Update Configuration${NC}
   Edit: ${APP_DIR}/api/config.php
   Set all credentials, API keys, and domain-specific settings

   Then copy to production:
   $ cp ${APP_DIR}/.env.example ${APP_DIR}/.env
   $ vi ${APP_DIR}/.env

3. ${BLUE}Set GitHub Webhook Secret${NC}
   In GitHub repo Settings → Webhooks:
   - Payload URL: https://${DOMAIN}/deploy/webhook.php
   - Content Type: application/json
   - Secret: (from .env GITHUB_WEBHOOK_SECRET)
   - Events: Push

4. ${BLUE}Test Application${NC}
   $ curl -I https://${DOMAIN}/
   Should return 200 OK with Fogbreak HTML

5. ${BLUE}Monitor Logs${NC}
   Nginx:        tail -f /var/log/nginx/fogbreak-access.log
   PHP-FPM:      tail -f /var/log/php/fogbreak-error.log
   Cron:         tail -f /var/log/fogbreak/cron.log
   Webhook:      tail -f /var/log/fogbreak/webhook.log

6. ${BLUE}Initialize Ollama (when ready for instruction 03)${NC}
   $ ollama pull llama2:70b
   $ ollama pull mistral:7b

   Then configure in .env:
   OLLAMA_API_URL=http://localhost:11434

7. ${BLUE}Set Up FastAPI AI Proxy (instruction 03)${NC}
   Create Python venv and install dependencies
   Enable systemd service: systemctl enable fogbreak-ai-proxy

8. ${BLUE}Database Migrations${NC}
   Run any pending migrations from code
   Test API endpoints: curl https://${DOMAIN}/api/admin.php?action=status

9. ${BLUE}Set Up Cron Authentication${NC}
   Update .env CRON_API_KEY and CRON_SECRET
   Cron runs: */15 * * * * /api/cron.php
   Verify: tail /var/log/fogbreak/cron.log

10. ${BLUE}Read Deployment Documentation${NC}
    - CLAUDE.md (project instructions)
    - ARCHITECTURE.html (system design)
    - 00-MASTER-PLAN.md (build roadmap)

${YELLOW}⚠ Important Security Notes${NC}
  - Never commit config.php or .env to Git
  - Database password should be at least 32 chars (use: openssl rand -base64 32)
  - GitHub token should have 'repo' scope only
  - Webhook secret should be 32+ chars
  - SSH access: ${DEPLOY_USER} user created (SSH key-only recommended)

${YELLOW}⚠ Critical Files to Backup${NC}
  - ${APP_DIR}/api/config.php
  - ${APP_DIR}/.env
  - Database: mysqldump fogbreak > backup.sql
  - SSL certs: /etc/letsencrypt/live/${DOMAIN}/
  - Cron logs: /var/log/fogbreak/

${BLUE}System Resources${NC}
  - Check: df -h (disk space)
  - Check: free -h (memory)
  - Check: htop (processes)
  - Check: netstat -tlnp (listening ports)

${GREEN}================================================================================
  Setup completed at $(date)
  For support, see: CLAUDE.md in project root
=================================================================================${NC}

EOF

# ============================================================================
# SAVE DEPLOYMENT SUMMARY
# ============================================================================

cat > "${APP_DIR}/DEPLOYMENT-SUMMARY.txt" << EOF
Fogbreak Server Setup Summary
Generated: $(date)
Domain: ${DOMAIN}
GitHub Repo: ${GITHUB_REPO}

Installation Details:
- OS: Ubuntu 24.04 LTS
- PHP 8.3-FPM
- MySQL 8.0 (fogbreak database)
- PostgreSQL 16 (ready)
- Nginx with SSL
- Redis cache
- Node.js 22 LTS
- Ollama AI inference
- Python 3.12 FastAPI

Critical Configuration Files:
- API Config: ${APP_DIR}/api/config.php
- Environment: ${APP_DIR}/.env
- Nginx: /etc/nginx/sites-available/${DOMAIN}
- Cron: /etc/cron.d/fogbreak-cron

Logs:
- Nginx Access: /var/log/nginx/fogbreak-access.log
- Nginx Error: /var/log/nginx/fogbreak-error.log
- PHP-FPM Error: /var/log/php/fogbreak-error.log
- Fogbreak Cron: /var/log/fogbreak/cron.log
- Webhook: /var/log/fogbreak/webhook.log

Database:
- Name: fogbreak
- User: fogbreak_app
- Host: localhost
- Port: 3306

Next Steps:
1. Configure ${APP_DIR}/api/config.php with all credentials
2. Set up GitHub webhook secret
3. Verify SSL certificate
4. Test application endpoints
5. Monitor logs for errors
6. When ready, proceed with instruction 02 (DB migration)

See CLAUDE.md for full instructions.
EOF

log_success "Deployment summary saved to ${APP_DIR}/DEPLOYMENT-SUMMARY.txt"

exit 0
