#!/bin/bash

# PHI|OS Uniphil.ch SSL Setup
# Sets up SSL certificates using Certbot and updates nginx for HTTPS

set -e

# Configuration
DOMAIN="uniphil.ch"
NGINX_AVAILABLE="/etc/nginx/sites-available/${DOMAIN}.conf"
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 SSL setup...${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

# Check if nginx config exists
if [ ! -f "${NGINX_AVAILABLE}" ]; then
    echo -e "${RED}[ERROR] Nginx configuration for ${DOMAIN} not found. Run nginx setup first.${NC}"
    exit 1
fi

# 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} -d www.${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

# Update nginx configuration for HTTPS
echo -e "${YELLOW}[NGINX] Updating configuration for HTTPS...${NC}"

# Backup current config
cp "${NGINX_AVAILABLE}" "${NGINX_AVAILABLE}.backup-$(date +%Y%m%d-%H%M%S)"

# Create HTTPS configuration
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;
    
    root /rhiz/PHI|OS/app/web;
    index index.html;
    
    location / {
        try_files \$uri \$uri/ =404;
    }
    
    # API proxy to PHI|OS services
    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;
    }
    
    # Static asset caching
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files \$uri =404;
    }
}
EONGINXHTTPS

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

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

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

# 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

echo -e "${GREEN}"
echo -e "╔════════════════════════════════════════════════════════════╗"
echo -e "║        PHI|OS Uniphil.ch SSL Setup Complete                ║"
echo -e "║                                                           ║"
echo -e "║  Domain: https://uniphil.ch                              ║"
echo -e "║  SSL: Let's Encrypt certificates installed               ║"
echo -e "║  HTTPS: TLS 1.2/1.3 with modern ciphers                 ║"
echo -e "║  Security: Headers and HSTS configured                   ║"
echo -e "║  Renewal: Automatic renewal configured                   ║"
echo -e "║                                                           ║"
echo -e "║  Your site is now secure and available at:              ║"
echo -e "║  https://uniphil.ch                                      ║"
echo -e "║                                                           ║"
echo -e "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

exit 0
