#!/bin/bash
# Putom po Zagrebu — nginx setup script
# Run with: curl -s https://files.surlan.pro/f/setup.sh | sudo bash
set -e

DOMAIN="putompozagrebu.surlan.pro"
WEBROOT="/var/www/putompozagrebu"
FILES_BASE="https://files.surlan.pro/f"

echo "=== Setting up $DOMAIN ==="

# 1. Create webroot
mkdir -p "$WEBROOT"

# 2. Download all files
echo "Downloading files..."
curl -sL "$FILES_BASE/index.html"            -o "$WEBROOT/index.html"
curl -sL "$FILES_BASE/sw.js"                 -o "$WEBROOT/sw.js"
curl -sL "$FILES_BASE/manifest.webmanifest"  -o "$WEBROOT/manifest.webmanifest"
curl -sL "https://putempozgu.andric.studio/static/putempozgu_loading_mob.png" -o "$WEBROOT/loading_mob.png"
curl -sL "https://putempozgu.andric.studio/static/putempozgu_loading_pc.png"  -o "$WEBROOT/loading_pc.png"

# 3. Write nginx config
cat > /etc/nginx/sites-available/$DOMAIN << 'NGINX'
server {
    listen 80;
    server_name putompozagrebu.surlan.pro;
    root /var/www/putompozagrebu;
    index index.html;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header Referrer-Policy "strict-origin-when-cross-origin";

    # Cache static assets
    location ~* \.(png|jpg|svg|ico|webp|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

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

    # Manifest
    location = /manifest.webmanifest {
        default_type application/manifest+json;
        add_header Cache-Control "no-cache";
    }

    # All routes serve index.html (SPA)
    location / {
        try_files $uri $uri/ /index.html;
    }
}
NGINX

# 4. Enable site
ln -sf /etc/nginx/sites-available/$DOMAIN /etc/nginx/sites-enabled/$DOMAIN

# 5. Test and reload nginx
nginx -t && systemctl reload nginx

echo ""
echo "=== Done! Site is serving on http://$DOMAIN ==="
echo ""
echo "Next step: get HTTPS with Let's Encrypt:"
echo "  certbot --nginx -d $DOMAIN"
echo ""
echo "Don't forget to point DNS:"
echo "  $DOMAIN  A  $(curl -s ifconfig.me)"
