#!/bin/bash
# Install systemd service for continuous leak monitoring
#
# Usage: install-leak-monitor.sh <container> [--type tor|vpn|wireguard]
#
# Creates a systemd service that monitors the specified container
# for network leaks and logs them to /var/log/gaol/

set -e

CONTAINER=""
PRIVACY_TYPE="tor"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="/var/log/gaol"
SERVICE_NAME=""

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

usage() {
    cat << EOF
Install Leak Monitor Systemd Service

Usage: $0 <container> [options]

Options:
  --type, -t <type>    Privacy type: tor, vpn, wireguard (default: tor)
  --uninstall, -u      Remove the service
  --status, -s         Show service status
  --help, -h           Show this help

Examples:
  $0 tor-browser                    # Install monitor for tor-browser
  $0 vpn-gateway --type vpn         # Install monitor for VPN container
  $0 tor-browser --uninstall        # Remove the service
  $0 tor-browser --status           # Check service status
EOF
    exit 1
}

log() { echo -e "${CYAN}[install]${NC} $1"; }
error() { echo -e "${RED}[install]${NC} $1"; }

# Parse arguments
ACTION="install"
while [[ $# -gt 0 ]]; do
    case $1 in
        --type|-t)
            PRIVACY_TYPE="$2"
            shift 2
            ;;
        --uninstall|-u)
            ACTION="uninstall"
            shift
            ;;
        --status|-s)
            ACTION="status"
            shift
            ;;
        --help|-h)
            usage
            ;;
        -*)
            error "Unknown option: $1"
            usage
            ;;
        *)
            if [[ -z "$CONTAINER" ]]; then
                CONTAINER="$1"
            fi
            shift
            ;;
    esac
done

if [[ -z "$CONTAINER" ]]; then
    error "Container name required"
    usage
fi

SERVICE_NAME="gaol-leak-monitor@${CONTAINER}"

do_install() {
    log "Installing leak monitor service for: $CONTAINER"

    # Create log directory
    sudo mkdir -p "$LOG_DIR"
    sudo chmod 755 "$LOG_DIR"

    # Copy monitor script if not in standard location
    MONITOR_SCRIPT="$SCRIPT_DIR/monitor-leaks.sh"
    if [[ ! -f "$MONITOR_SCRIPT" ]]; then
        error "Monitor script not found: $MONITOR_SCRIPT"
        exit 1
    fi

    # Install script to /usr/local/bin
    sudo cp "$MONITOR_SCRIPT" /usr/local/bin/gaol-monitor-leaks
    sudo chmod 755 /usr/local/bin/gaol-monitor-leaks

    # Create systemd service template
    log "Creating systemd service template..."
    sudo tee /etc/systemd/system/gaol-leak-monitor@.service > /dev/null << 'EOF'
[Unit]
Description=Gaol Network Leak Monitor for %i
After=systemd-nspawn@%i.service
Wants=systemd-nspawn@%i.service
PartOf=systemd-nspawn@%i.service

[Service]
Type=simple
ExecStart=/usr/local/bin/gaol-monitor-leaks %i --log /var/log/gaol/%i-leaks.log
Restart=on-failure
RestartSec=10

# Allow reading /var/log/messages for leak detection
ReadOnlyPaths=/var/log

[Install]
WantedBy=systemd-nspawn@%i.service
EOF

    # Create a config file for container-specific settings
    log "Creating configuration for $CONTAINER..."
    sudo mkdir -p /etc/gaol/leak-monitor
    sudo tee "/etc/gaol/leak-monitor/${CONTAINER}.conf" > /dev/null << EOF
# Leak monitor configuration for $CONTAINER
PRIVACY_TYPE=$PRIVACY_TYPE
# Add VPN_SERVER_IP for VPN containers
# Add WG_ENDPOINT for WireGuard containers
EOF

    # Reload systemd
    sudo systemctl daemon-reload

    # Enable and start the service
    log "Enabling service..."
    sudo systemctl enable "gaol-leak-monitor@${CONTAINER}.service"

    log "Starting service..."
    sudo systemctl start "gaol-leak-monitor@${CONTAINER}.service"

    echo ""
    log "Service installed successfully!"
    log "Log file: $LOG_DIR/${CONTAINER}-leaks.log"
    log "Config: /etc/gaol/leak-monitor/${CONTAINER}.conf"
    echo ""
    log "Commands:"
    log "  Status:  sudo systemctl status gaol-leak-monitor@${CONTAINER}"
    log "  Logs:    sudo journalctl -u gaol-leak-monitor@${CONTAINER} -f"
    log "  Stop:    sudo systemctl stop gaol-leak-monitor@${CONTAINER}"
}

do_uninstall() {
    log "Removing leak monitor service for: $CONTAINER"

    # Stop and disable service
    sudo systemctl stop "gaol-leak-monitor@${CONTAINER}.service" 2>/dev/null || true
    sudo systemctl disable "gaol-leak-monitor@${CONTAINER}.service" 2>/dev/null || true

    # Remove config
    sudo rm -f "/etc/gaol/leak-monitor/${CONTAINER}.conf"

    log "Service removed"
    log "Note: Log file preserved at $LOG_DIR/${CONTAINER}-leaks.log"
    log "Note: Service template preserved (may be used by other containers)"
}

do_status() {
    echo ""
    echo "=== Leak Monitor Status: $CONTAINER ==="
    echo ""

    # Service status
    if systemctl is-active --quiet "gaol-leak-monitor@${CONTAINER}.service"; then
        echo -e "Service: ${GREEN}RUNNING${NC}"
    else
        echo -e "Service: ${RED}STOPPED${NC}"
    fi

    # Log file
    LOG_FILE="$LOG_DIR/${CONTAINER}-leaks.log"
    if [[ -f "$LOG_FILE" ]]; then
        LEAK_COUNT=$(wc -l < "$LOG_FILE" 2>/dev/null || echo "0")
        echo "Leaks logged: $LEAK_COUNT"

        if [[ $LEAK_COUNT -gt 0 ]]; then
            echo ""
            echo "Recent leaks:"
            tail -5 "$LOG_FILE" | while read line; do
                echo "  $line"
            done
        fi
    else
        echo "Log file: Not found"
    fi

    echo ""

    # Full systemd status
    sudo systemctl status "gaol-leak-monitor@${CONTAINER}.service" --no-pager 2>/dev/null || true
}

# Run action
case $ACTION in
    install)
        do_install
        ;;
    uninstall)
        do_uninstall
        ;;
    status)
        do_status
        ;;
esac
