#!/bin/bash
# ============================================================
# chqcode.dev - Setup Script
# Generated by NginxForge
# Preset: Static Site
# Generated: 2026-01-20 21:14:43 UTC
# ============================================================

set -euo pipefail

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# Check root
[[ $EUID -ne 0 ]] && log_error "This script must be run as root"

DOMAIN="chqcode.dev"
ROOT_PATH="/var/www/chqcode.dev"
NGINX_CONF="/etc/nginx/sites-available/${DOMAIN}"
NGINX_ENABLED="/etc/nginx/sites-enabled/${DOMAIN}"

log_info "Starting setup for ${DOMAIN}..."

# ============================================================
# 1. Install dependencies
# ============================================================
log_info "Installing dependencies..."

apt-get update -qq

PACKAGES="nginx"
PACKAGES="$PACKAGES certbot python3-certbot-nginx"

apt-get install -y -qq $PACKAGES
log_success "Dependencies installed"

# ============================================================
# 2. Create directories
# ============================================================
log_info "Creating directories..."

mkdir -p "${ROOT_PATH}"
mkdir -p /var/www/certbot
mkdir -p /var/log/nginx

chown -R www-data:www-data "${ROOT_PATH}"
chmod -R 755 "${ROOT_PATH}"

log_success "Directories created"

# ============================================================
# 3. Deploy nginx configuration
# ============================================================
log_info "Deploying nginx configuration..."

cat > "${NGINX_CONF}" << 'NGINX_CONFIG'
# chqcode.dev - Generated by NginxForge
# Preset: Static Site
# Generated: 2026-01-20 21:14:43 UTC

limit_req_zone $binary_remote_addr zone=one:10m rate=10000r/s;


# HTTP -> HTTPS redirect
server {
    listen 80;
    listen [::]:80;
    server_name chqcode.dev;
    
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
        allow all;
    }
    
    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    
    ssl_certificate /etc/letsencrypt/live/chqcode.dev/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/chqcode.dev/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    server_name chqcode.dev;
    root /var/www/chqcode.dev;
    index index.html index.htm;

    server_tokens off;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Content-Security-Policy "upgrade-insecure-requests" always;

    # Allowed methods
    if ($request_method !~ ^(GET|POST|HEAD)$) {
        return 405;
    }

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 1000;
    gzip_types
        application/atom+xml
        application/javascript
        application/json
        application/ld+json
        application/manifest+json
        application/rss+xml
        application/vnd.geo+json
        application/vnd.ms-fontobject
        application/x-font-ttf
        application/x-web-app-manifest+json
        application/xhtml+xml
        application/xml
        font/opentype
        image/bmp
        image/svg+xml
        image/x-icon
        text/cache-manifest
        text/css
        text/plain
        text/vcard
        text/vnd.rim.location.xloc
        text/vtt
        text/x-component
        text/x-cross-domain-policy
        text/xml;
    limit_req zone=one burst=50 nodelay;

    client_max_body_size 64m;

    # Static site configuration
    location / {
        try_files $uri $uri/ =404;
    }
    # Static file caching
    location ~* \.(jpg|jpeg|png|gif|ico|webp|svg|woff|woff2|ttf|eot|otf)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        access_log off;
        log_not_found off;
    }

    location ~* \.(css|js)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    location ~* \.(pdf|doc|docx|xls|xlsx|zip|rar|gz|tar)$ {
        expires 7d;
        add_header Cache-Control "public";
    }
    # Deny access to hidden files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    access_log /var/log/nginx/chqcode.dev.access.log;
    error_log /var/log/nginx/chqcode.dev.error.log;
}
NGINX_CONFIG

# Enable site
ln -sf "${NGINX_CONF}" "${NGINX_ENABLED}"

# Test configuration
nginx -t || log_error "Nginx configuration test failed"

log_success "Nginx configuration deployed"

# ============================================================
# 4. SSL Certificate
# ============================================================
log_info "Obtaining SSL certificate from Let's Encrypt..."

# First, reload nginx with HTTP-only config for ACME challenge
systemctl reload nginx

certbot certonly \
    --nginx \
    -d chqcode.dev \
    --email jill.nova@bk.ru \
    --agree-tos \
    --non-interactive \
    --redirect

# Setup auto-renewal
systemctl enable certbot.timer
systemctl start certbot.timer

log_success "SSL certificate obtained and auto-renewal configured"

# ============================================================
# 5. Configure firewall
# ============================================================
log_info "Configuring firewall..."

if command -v ufw &> /dev/null; then
    ufw allow 'Nginx Full' || true
    log_success "UFW configured"
else
    log_warn "UFW not installed, skipping firewall configuration"
fi

# ============================================================
# 6. Start/Reload services
# ============================================================
log_info "Starting services..."

systemctl enable nginx
systemctl reload nginx


log_success "Services started"

# ============================================================
# 7. Create test page
# ============================================================
if [[ ! -f "${ROOT_PATH}/index.html" ]]; then
    cat > "${ROOT_PATH}/index.html" << 'HTML'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>chqcode.dev</title>
    <style>
        body { font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .container { text-align: center; padding: 2rem; }
        h1 { font-size: 3rem; margin-bottom: 0.5rem; }
        p { opacity: 0.9; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 chqcode.dev</h1>
        <p>Successfully deployed with NginxForge</p>
    </div>
</body>
</html>
HTML
    chown www-data:www-data "${ROOT_PATH}/index.html"
    log_success "Test page created"
fi

# ============================================================
# Summary
# ============================================================
echo ""
echo -e "${GREEN}============================================================${NC}"
echo -e "${GREEN} Setup Complete!${NC}"
echo -e "${GREEN}============================================================${NC}"
echo ""
echo -e "Domain:     ${BLUE}chqcode.dev${NC}"
echo -e "URL:        ${BLUE}https://chqcode.dev${NC}"
echo -e "Root:       ${BLUE}${ROOT_PATH}${NC}"
echo -e "Nginx conf: ${BLUE}${NGINX_CONF}${NC}"
echo -e "Access log: ${BLUE}/var/log/nginx/chqcode.dev.access.log${NC}"
echo -e "Error log:  ${BLUE}/var/log/nginx/chqcode.dev.error.log${NC}"
echo ""
