#!/usr/bin/env bash
set -euo pipefail

# Nginx Security Headers Config Generator
# Outputs a ready-to-include snippet for Nginx.
# Usage: curl -fsSL https://aaran.cloud/assets/scripts/nginx-security-headers.sh | bash

SNIPPET_PATH="/etc/nginx/snippets/security-headers.conf"

cat << 'EOF'
# Nginx Security Headers Snippet
# Include this in your server block:
#   include /etc/nginx/snippets/security-headers.conf;
#
# Add this inside a location / { ... } block or server block.

add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; form-action 'self'" always;

# Uncomment after confirming HTTPS is always used:
# add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
EOF

if [ "$(id -u)" -eq 0 ] && [ -d /etc/nginx/snippets ]; then
  cat << 'EOF' > "$SNIPPET_PATH"
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; form-action 'self'" always;
EOF
  echo ""
  echo "Snippet written to: $SNIPPET_PATH"
  echo "Test config with: nginx -t && systemctl reload nginx"
else
  echo ""
  echo "Run as root to auto-install to $SNIPPET_PATH, or copy the snippet above manually."
fi
