#!/bin/bash

# 'PHI|OS' Uniphil.ch Deployment Script
# Automates nginx configuration, SSL setup, and system genesis

set -e

# Configuration
DOMAIN="uniphil.ch"
NGINX_AVAILABLE="/etc/nginx/sites-available/${DOMAIN}.conf"
NGINX_ENABLED="/etc/nginx/sites-enabled/${DOMAIN}.conf"
WEB_ROOT="/rhiz/PHI|OS/app/web"
CERTBOT_EMAIL="admin@uniphil.ch"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${YELLOW}['PHI|OS'] Starting Uniphil.ch deployment...${NC}"

# Check if running as root
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}[ERROR] This script must be run as root${NC}"
    exit 1
fi

# Create nginx configuration
echo -e "${YELLOW}[NGINX] Creating configuration for ${DOMAIN}...${NC}"
cat > "${NGINX_AVAILABLE}" << 'EONGINX'
server {
    listen 80;
    server_name uniphil.ch;
    
    # Proxy all requests to the PHI|OS container running on port 3300
    location / {
        proxy_pass http://localhost:3300;
        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;
    }
    
    # API proxy to PHI|OS services (port 3001)
    location /api/ {
        proxy_pass http://localhost:3001/api/;
        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;
    }
    
    # Websocket support for realtime features
    location /ws/ {
        proxy_pass http://localhost:3001/ws/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}
EONGINX

echo -e "${GREEN}[NGINX] Configuration created${NC}"

# Enable the site
echo -e "${YELLOW}[NGINX] Enabling site...${NC}"
if [ -f "${NGINX_ENABLED}" ]; then
    rm "${NGINX_ENABLED}"
fi
ln -s "${NGINX_AVAILABLE}" "${NGINX_ENABLED}"
echo -e "${GREEN}[NGINX] Site enabled${NC}"

# Test nginx configuration
echo -e "${YELLOW}[NGINX] Testing configuration...${NC}"
nginx -t
echo -e "${GREEN}[NGINX] Configuration test passed${NC}"

# Reload nginx
echo -e "${YELLOW}[NGINX] Reloading nginx...${NC}"
systemctl reload nginx
echo -e "${GREEN}[NGINX] Nginx reloaded${NC}"

# Install certbot if not installed
echo -e "${YELLOW}[SSL] Checking certbot installation...${NC}"
if ! command -v certbot &> /dev/null; then
    echo -e "${YELLOW}[SSL] Installing certbot...${NC}"
    apt-get update
    apt-get install -y certbot python3-certbot-nginx
    echo -e "${GREEN}[SSL] Certbot installed${NC}"
fi

# Obtain SSL certificate
echo -e "${YELLOW}[SSL] Requesting SSL certificate for ${DOMAIN}...${NC}"
if [ ! -d "/etc/letsencrypt/live/${DOMAIN}" ]; then
    certbot --nginx -d ${DOMAIN} --non-interactive --agree-tos --email ${CERTBOT_EMAIL}
    echo -e "${GREEN}[SSL] SSL certificate obtained${NC}"
else
    echo -e "${YELLOW}[SSL] SSL certificate already exists, skipping request${NC}"
fi

# Set up certbot renewal
echo -e "${YELLOW}[SSL] Setting up automatic certificate renewal...${NC}"
if [ ! -f "/etc/cron.d/certbot-renewal" ]; then
    cat > /etc/cron.d/certbot-renewal << 'EOCRON'
0 */12 * * * root certbot renew --quiet --no-self-upgrade
EOCRON
    echo -e "${GREEN}[SSL] Automatic renewal configured${NC}"
else
    echo -e "${YELLOW}[SSL] Automatic renewal already configured${NC}"
fi

# Update nginx configuration for HTTPS
echo -e "${YELLOW}[NGINX] Updating configuration for HTTPS...${NC}"
cat > "${NGINX_AVAILABLE}" << EONGINXHTTPS
server {
    listen 80;
    server_name uniphil.ch www.uniphil.ch;
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    server_name uniphil.ch www.uniphil.ch;
    
    ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/${DOMAIN}/chain.pem;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling on;
    ssl_stapling_verify on;
    
    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: ws: wss: data: blob: 'unsafe-inline' 'unsafe-eval'" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    
    # Proxy all requests to the PHI|OS container running on port 3300
    location / {
        proxy_pass http://localhost:3300;
        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;
    }
    
    # API proxy to PHI|OS services (port 3001)
    location /api/ {
        proxy_pass http://localhost:3001/api/;
        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;
    }
    
    # Websocket support for realtime features
    location /ws/ {
        proxy_pass http://localhost:3001/ws/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
    }
}
EONGINXHTTPS

echo -e "${GREEN}[NGINX] HTTPS configuration updated${NC}"

# Test and reload nginx again
echo -e "${YELLOW}[NGINX] Testing HTTPS configuration...${NC}"
nginx -t
echo -e "${GREEN}[NGINX] HTTPS configuration test passed${NC}"

echo -e "${YELLOW}[NGINX] Reloading nginx with HTTPS...${NC}"
systemctl reload nginx
echo -e "${GREEN}[NGINX] Nginx reloaded with HTTPS${NC}"

# Run 'PHI|OS' system genesis (will be handled by services-start.sh)
echo -e "${YELLOW}['PHI|OS'] System genesis will be handled by services script${NC}"

# Start 'PHI|OS' services
echo -e "${YELLOW}['PHI|OS'] Starting services...${NC}"
if [ -f "/rhiz/PHI|OS/deploy/services-start.sh" ]; then
    /rhiz/PHI|OS/deploy/services-start.sh
else
    cd /rhiz/factory/hypergraph_meta_cluster_bundle/services/webapp
    if [ -f "package.json" ]; then
        if [ -d "node_modules" ]; then
            npm run build
            npm run start &
        else
            echo -e "${YELLOW}['PHI|OS'] Installing dependencies...${NC}"
            npm install
            npm run build
            npm run start &
        fi
        echo -e "${GREEN}['PHI|OS'] Services started${NC}"
    else
        echo -e "${RED}[ERROR] 'PHI|OS' webapp not found${NC}"
    fi
fi

echo -e "${GREEN}"
echo -e "╔════════════════════════════════════════════════════════════╗"
echo -e "║           'PHI|OS' Uniphil.ch Deployment Complete           ║"
echo -e "║                                                           ║"
echo -e "║  Domain: https://uniphil.ch                               ║"
echo -e "║  Web Root: /rhiz/PHI|OS/app/web                           ║"
echo -e "║  Nginx Config: /etc/nginx/sites-available/uniphil.ch.conf ║"
echo -e "║  SSL: Let's Encrypt certificates installed                ║"
echo -e "║                                                           ║"
echo -e "║  Services should be running on:                          ║"
echo -e "║  - Web: https://uniphil.ch                               ║"
echo -e "║  - API: https://uniphil.ch/api/                          ║"
echo -e "║  - WS: wss://uniphil.ch/ws/                              ║"
echo -e "║                                                           ║"
echo -e "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

exit 0
