#!/bin/bash
###############################################################
#### Fix code-server Nginx Config                          ####
#### Applies X-Frame-Options + query-filter fixes          ####
####                                                       ####
#### Author: Phil Connor                                   ####
#### Contact: contact@mylinux.work                         ####
#### License: MIT                                          ####
#### Version: 1.0                                          ####
####                                                       ####
#### Usage: sudo ./fix-code-server-nginx.sh [domain]       ####
###############################################################
set -euo pipefail

if [[ $EUID -ne 0 ]]; then
    echo "ERROR: This script must be run as root (sudo)."
    exit 1
fi

DOMAIN="${1:-}"
if [[ -z "$DOMAIN" ]]; then
    read -rp "Enter the code-server domain (e.g. code.mydomain.com): " DOMAIN
fi

HEADERS_FILE="/etc/nginx/snippets/security-headers-${DOMAIN}.conf"
SITE_CONF="/etc/nginx/conf.d/code-server.conf"

echo "=== Fix 1: X-Frame-Options DENY -> SAMEORIGIN ==="
if [[ -f "$HEADERS_FILE" ]]; then
    if grep -q 'X-Frame-Options "DENY"' "$HEADERS_FILE"; then
        sed -i 's/X-Frame-Options "DENY"/X-Frame-Options "SAMEORIGIN"/' "$HEADERS_FILE"
        echo "  Updated: $HEADERS_FILE"
    else
        echo "  Already set to SAMEORIGIN (or not found) in $HEADERS_FILE — skipping."
    fi
else
    echo "  WARNING: $HEADERS_FILE not found. Skipping."
fi

echo ""
echo "=== Fix 2: Disable query-filter snippet ==="
QUERY_FILTER="snippets/query-filter-${DOMAIN}.conf"
if [[ -f "$SITE_CONF" ]]; then
    if grep -qE "^\s*include\s+${QUERY_FILTER}" "$SITE_CONF"; then
        sed -i "s|^\(\s*\)include ${QUERY_FILTER};|\1# Disabled: breaks VS Code extensions\n\1# include ${QUERY_FILTER};|" "$SITE_CONF"
        echo "  Commented out query filter in: $SITE_CONF"
    else
        echo "  Query filter already disabled (or not found) in $SITE_CONF — skipping."
    fi
else
    echo "  WARNING: $SITE_CONF not found. Skipping."
fi

echo ""
echo "=== Testing and reloading nginx ==="
if nginx -t; then
    systemctl reload nginx
    echo "  Nginx reloaded successfully."
else
    echo "  ERROR: nginx config test failed. Check the files manually."
    exit 1
fi

echo ""
echo "Done! Reload your code-server browser tab to verify."
