#!/bin/bash
# ============================================================
# plrk.dev - Setup Script
# Generated by NginxForge
# Preset: PHP-FPM
# Generated: 2026-01-20 21:10:49 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="plrk.dev"
ROOT_PATH="/var/www/plrk.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"
PACKAGES="$PACKAGES php8.3-fpm php8.3-cli php8.3-common php8.3-mysql php8.3-xml php8.3-curl php8.3-gd php8.3-mbstring php8.3-zip php8.3-intl"

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'
# plrk.dev - Generated by NginxForge
# Preset: PHP-FPM
# Generated: 2026-01-20 21:10:48 UTC



# HTTP -> HTTPS redirect
server {
    listen 80;
    listen [::]:80;
    server_name plrk.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/plrk.dev/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/plrk.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 plrk.dev;
    root /var/www/plrk.dev;
    index index.html index.htm index.php;

    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;

    client_max_body_size 64m;

    # PHP-FPM configuration
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        include fastcgi_params;
        
        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout 60s;
        fastcgi_read_timeout 60s;
        fastcgi_buffer_size 4k;
        fastcgi_buffers 8 4k;
    }
    # 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/plrk.dev.access.log;
    error_log /var/log/nginx/plrk.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 plrk.dev \
    --register-unsafely-without-email \
    --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

systemctl enable php8.3-fpm
systemctl restart php8.3-fpm

log_success "Services started"

# ============================================================
# 7. Create test page
# ============================================================
if [[ ! -f "${ROOT_PATH}/index.php" ]]; then
    echo '<?php phpinfo();' > "${ROOT_PATH}/index.php"
    chown www-data:www-data "${ROOT_PATH}/index.php"
    log_success "PHP 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}plrk.dev${NC}"
echo -e "URL:        ${BLUE}https://plrk.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/plrk.dev.access.log${NC}"
echo -e "Error log:  ${BLUE}/var/log/nginx/plrk.dev.error.log${NC}"
echo ""
