#!/bin/bash

set -e

case "$1" in
    configure)
        echo "Configuring wild-central..."

        # Create wildcloud user if it doesn't exist
        if ! id wildcloud >/dev/null 2>&1; then
            useradd --system --home-dir /var/lib/wild-central --create-home --shell /bin/false wildcloud
        fi

        # Create required directories
        mkdir -p /var/lib/wild-central
        mkdir -p /var/log/wild-central
        mkdir -p /etc/wild-central

        # Set ownership
        chown -R wildcloud:wildcloud /var/lib/wild-central
        chown wildcloud:wildcloud /var/log/wild-central

        # Set up dnsmasq directories and permissions
        mkdir -p /etc/dnsmasq.d
        mkdir -p /etc/dnsmasq.d/wild-cloud-instances

        # Give wildcloud group write access to dnsmasq.d directory
        chgrp wildcloud /etc/dnsmasq.d
        chmod 775 /etc/dnsmasq.d

        # Create or fix ownership of wild-central.conf
        if [ ! -f /etc/dnsmasq.d/wild-central.conf ]; then
            touch /etc/dnsmasq.d/wild-central.conf
            echo "Created /etc/dnsmasq.d/wild-central.conf"
        else
            echo "Found existing /etc/dnsmasq.d/wild-central.conf - updating ownership"
        fi

        chown wildcloud:wildcloud /etc/dnsmasq.d/wild-central.conf
        chmod 644 /etc/dnsmasq.d/wild-central.conf

        # Set ownership and permissions for instance configs directory
        chown wildcloud:wildcloud /etc/dnsmasq.d/wild-cloud-instances
        chmod 755 /etc/dnsmasq.d/wild-cloud-instances
        echo "Created /etc/dnsmasq.d/wild-cloud-instances/ for per-instance DNS configs"

        # Set up systemd-resolved configuration directory and file
        mkdir -p /etc/systemd/resolved.conf.d

        if [ ! -f /etc/systemd/resolved.conf.d/wild-central.conf ]; then
            touch /etc/systemd/resolved.conf.d/wild-central.conf
            echo "Created /etc/systemd/resolved.conf.d/wild-central.conf"
        else
            echo "Found existing /etc/systemd/resolved.conf.d/wild-central.conf"
        fi
        chown wildcloud:wildcloud /etc/systemd/resolved.conf.d/wild-central.conf
        chmod 644 /etc/systemd/resolved.conf.d/wild-central.conf

        # Ensure /etc/resolv.conf is a symlink to systemd-resolved stub
        # Skip in Docker/container environments where resolv.conf might be bind-mounted
        if [ ! -L /etc/resolv.conf ] || [ "$(readlink /etc/resolv.conf)" != "/run/systemd/resolve/stub-resolv.conf" ]; then
            echo "Configuring /etc/resolv.conf to use systemd-resolved stub mode"
            if [ -f /etc/resolv.conf ] && [ ! -L /etc/resolv.conf ]; then
                cp /etc/resolv.conf /etc/resolv.conf.wild-backup 2>/dev/null || echo "Note: Could not backup /etc/resolv.conf (may be read-only)"
            fi
            if rm -f /etc/resolv.conf 2>/dev/null; then
                ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
                echo "Set /etc/resolv.conf to use systemd-resolved stub mode"
            else
                echo "Note: /etc/resolv.conf is read-only or busy (container environment?), skipping symlink setup"
            fi
        fi

        # Set up HAProxy configuration directory
        mkdir -p /etc/haproxy
        if [ ! -f /etc/haproxy/haproxy.cfg ]; then
            touch /etc/haproxy/haproxy.cfg
            echo "Created /etc/haproxy/haproxy.cfg"
        fi
        chown wildcloud:wildcloud /etc/haproxy
        chown wildcloud:wildcloud /etc/haproxy/haproxy.cfg
        chmod 644 /etc/haproxy/haproxy.cfg

        # Set up HAProxy TLS certs directory
        mkdir -p /etc/haproxy/certs
        chown wildcloud:wildcloud /etc/haproxy/certs
        chmod 700 /etc/haproxy/certs
        echo "Configured HAProxy for Wild Central management"

        # Set up WireGuard configuration directory
        mkdir -p /etc/wireguard
        chown wildcloud:wildcloud /etc/wireguard
        chmod 700 /etc/wireguard
        if [ ! -f /etc/wireguard/wg0.conf ]; then
            touch /etc/wireguard/wg0.conf
            echo "Created /etc/wireguard/wg0.conf"
        fi
        chown wildcloud:wildcloud /etc/wireguard/wg0.conf
        chmod 600 /etc/wireguard/wg0.conf
        echo "Configured WireGuard for Wild Central management"

        # Set up nftables configuration directory
        mkdir -p /etc/nftables.d
        if [ ! -f /etc/nftables.d/wild-central.nft ]; then
            touch /etc/nftables.d/wild-central.nft
            echo "Created /etc/nftables.d/wild-central.nft"
        fi
        chown wildcloud:wildcloud /etc/nftables.d/wild-central.nft
        chmod 644 /etc/nftables.d/wild-central.nft

        # Ensure nftables.conf includes wild-central rules
        if [ -f /etc/nftables.conf ] && ! grep -q 'wild-central.nft' /etc/nftables.conf; then
            echo 'include "/etc/nftables.d/wild-central.nft"' >> /etc/nftables.conf
            echo "Added Wild Central nftables include to /etc/nftables.conf"
        fi
        echo "Configured nftables for Wild Central management"

        # Install CrowdSec if not already installed
        if ! command -v cscli >/dev/null 2>&1; then
            echo "Installing CrowdSec..."
            curl -s https://packagecloud.io/install/repositories/crowdsec/crowdsec/script.deb.sh | os=ubuntu dist=noble bash
            apt-get install -y crowdsec
            echo "Installed CrowdSec"
        else
            echo "CrowdSec already installed: $(cscli version 2>/dev/null | head -1 || echo 'unknown')"
        fi

        # Configure CrowdSec LAPI to listen on all interfaces
        CROWDSEC_CONFIG=/etc/crowdsec/config.yaml
        if [ -f "$CROWDSEC_CONFIG" ] && command -v yq >/dev/null 2>&1; then
            yq e -i '.api.server.listen_uri = "0.0.0.0:8080"' "$CROWDSEC_CONFIG"
            echo "Configured CrowdSec LAPI to listen on 0.0.0.0:8080"
        fi

        # Ensure CrowdSec is running so the firewall bouncer can register with LAPI
        if [ -d /run/systemd/system ]; then
            systemctl start crowdsec 2>/dev/null || true
            sleep 2
        fi

        # Install CrowdSec firewall bouncer
        if ! command -v crowdsec-firewall-bouncer >/dev/null 2>&1; then
            echo "Installing CrowdSec firewall bouncer..."
            apt-get install -y crowdsec-firewall-bouncer
            echo "Installed CrowdSec firewall bouncer"
        else
            echo "CrowdSec firewall bouncer already installed"
        fi

        # Install Authelia if not already installed
        if ! command -v authelia >/dev/null 2>&1; then
            echo "Installing Authelia..."
            curl -fsSL https://apt.authelia.com/organization/signing.asc | \
                gpg --dearmor -o /usr/share/keyrings/authelia-archive-keyring.gpg
            echo "deb [signed-by=/usr/share/keyrings/authelia-archive-keyring.gpg] \
                https://apt.authelia.com/integration/apt/repo/stable/debian debian main" \
                > /etc/apt/sources.list.d/authelia.list
            apt-get update -qq
            apt-get install -y authelia
            echo "Installed Authelia"
        else
            echo "Authelia already installed"
        fi

        # Install HAProxy Lua scripts for Authelia auth-request forwarding
        mkdir -p /etc/haproxy/lua
        if [ ! -f /etc/haproxy/lua/haproxy-auth-request.lua ]; then
            curl -fsSL -o /etc/haproxy/lua/haproxy-auth-request.lua \
                https://raw.githubusercontent.com/TimWolla/haproxy-auth-request/main/auth-request.lua
            echo "Installed haproxy-auth-request.lua"
        fi
        if [ ! -f /etc/haproxy/lua/haproxy-lua-http.lua ]; then
            curl -fsSL -o /etc/haproxy/lua/haproxy-lua-http.lua \
                https://raw.githubusercontent.com/haproxytech/haproxy-lua-http/master/http.lua
            echo "Installed haproxy-lua-http.lua"
        fi
        apt-get install -y lua-json 2>/dev/null || true

        # Configure Authelia systemd override to use Wild Central config path
        mkdir -p /etc/systemd/system/authelia.service.d
        cat > /etc/systemd/system/authelia.service.d/wild-central.conf << 'AUTHELIA_EOF'
[Service]
ExecStart=
ExecStart=/usr/bin/authelia --config /var/lib/wild-central/authelia/configuration.yml
AUTHELIA_EOF
        echo "Configured Authelia systemd override"

        # Create Authelia data directory
        mkdir -p /var/lib/wild-central/authelia
        chown wildcloud:wildcloud /var/lib/wild-central/authelia
        chmod 700 /var/lib/wild-central/authelia

        # Install sudoers rules for privileged operations
        cat > /etc/sudoers.d/wild-central << 'SUDOERS_EOF'
wildcloud ALL=(ALL) NOPASSWD: /usr/sbin/nft -c -f *, /usr/sbin/nft list table inet wild-central, /usr/bin/cscli bouncers *, /usr/bin/cscli machines *, /usr/bin/cscli decisions *, /usr/bin/cscli alerts *, /usr/bin/cscli version, /usr/bin/wg-quick up wg0, /usr/bin/wg-quick down wg0, /usr/bin/wg show wg0, /usr/bin/certbot *, /usr/sbin/nginx -t, /usr/bin/systemctl reload nginx
SUDOERS_EOF
        chmod 440 /etc/sudoers.d/wild-central
        echo "Installed sudoers rules for Wild Central"

        # Install polkit rules for service management
        mkdir -p /etc/polkit-1/rules.d
        cat > /etc/polkit-1/rules.d/50-wild-central.rules << 'POLKIT_EOF'
/* Allow wildcloud user to manage Wild Central services */
polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.systemd1.manage-units" &&
        (action.lookup("unit") == "dnsmasq.service" ||
         action.lookup("unit") == "systemd-resolved.service" ||
         action.lookup("unit") == "haproxy.service" ||
         action.lookup("unit") == "wild-central-nftables-reload.service" ||
         action.lookup("unit") == "crowdsec.service" ||
         action.lookup("unit") == "crowdsec-firewall-bouncer.service" ||
         action.lookup("unit") == "wg-quick@wg0.service" ||
         action.lookup("unit") == "cloudflared.service" ||
         action.lookup("unit") == "authelia.service" ||
         action.lookup("unit") == "wild-central.service") &&
        subject.user == "wildcloud") {
        return polkit.Result.YES;
    }
});
POLKIT_EOF
        chmod 644 /etc/polkit-1/rules.d/50-wild-central.rules
        echo "Installed polkit rules for service management"

        # Enable nginx site (disable default site, enable wild-central)
        if [ -f /etc/nginx/sites-enabled/default ]; then
            rm -f /etc/nginx/sites-enabled/default
            echo "Disabled default nginx site"
        fi
        if [ ! -L /etc/nginx/sites-enabled/wild-central ]; then
            ln -sf /etc/nginx/sites-available/wild-central /etc/nginx/sites-enabled/wild-central
            echo "Enabled wild-central nginx site"
        fi

        # Reload nginx to pick up the new site
        if systemctl is-active --quiet nginx; then
            nginx -t && systemctl reload nginx
            echo "Reloaded nginx configuration"
        fi

        # Enable and start the service
        if [ -d /run/systemd/system ]; then
            systemctl daemon-reload
            systemctl enable wild-central.service
            echo "wild-central configured successfully"
            echo "Start the service with: sudo systemctl start wild-central"
            echo "View logs with: sudo journalctl -u wild-central -f"
        else
            echo "Note: systemd not detected (container environment?), skipping service enable"
            echo "wild-central installed successfully"
        fi
        ;;

    abort-upgrade|abort-remove|abort-deconfigure)
        ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
        ;;
esac

exit 0
