#!/bin/bash
#
# Nuke Network Monitoring and Alert Script
# Monitors Nuke processes for external network connections and alerts when found
#
# Usage:
#   bash monitor_nuke_network.sh              # Run one-time check
#   bash monitor_nuke_network.sh --continuous # Run continuously (Ctrl+C to stop)
#   bash monitor_nuke_network.sh --daemon     # Run as background daemon
#
# Cron installation (check every 5 minutes):
#   */5 * * * * /home/nicholai/Documents/obsidian-vault/2-projects/Nuke-monitoring/scripts/monitor_nuke_network.sh >> /tmp/nuke_monitor.log 2>&1
#

# Configuration
ALERT_LOG="/home/nicholai/Documents/obsidian-vault/2-projects/Nuke-monitoring/nuke_telemetry_alerts.log"
CHECK_INTERVAL=5  # seconds for continuous mode

# Known Foundry domains and IPs (for enhanced alerting)
declare -A KNOWN_ENDPOINTS=(
    ["52.50.232.31"]="learn.foundry.com"
    ["52.205.16.9"]="api.honeycomb.io"
)

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

log_alert() {
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')

    # Log to file
    echo "[$timestamp] $message" >> "$ALERT_LOG"

    # Print to console
    echo -e "${RED}[ALERT]${NC} $message"

    # Desktop notification (if in X session)
    if [ -n "$DISPLAY" ] && command -v notify-send &>/dev/null; then
        notify-send -u critical "Nuke Telemetry Alert" "$message"
    fi
}

log_info() {
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')

    echo -e "${BLUE}[INFO]${NC} [$timestamp] $message"
}

log_success() {
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')

    echo -e "${GREEN}[OK]${NC} [$timestamp] $message"
}

get_nuke_pids() {
    # Find all Nuke processes (handles various process names)
    pgrep -f "Nuke15\\.2|Nuke15\\.2v6|/Nuke$" 2>/dev/null
}

resolve_ip_to_domain() {
    local ip="$1"

    # Check known endpoints first
    if [ -n "${KNOWN_ENDPOINTS[$ip]}" ]; then
        echo "${KNOWN_ENDPOINTS[$ip]}"
        return
    fi

    # Try reverse DNS lookup
    local domain=$(dig -x "$ip" +short 2>/dev/null | head -1)

    if [ -n "$domain" ]; then
        echo "$domain"
    else
        echo "unknown"
    fi
}

check_nuke_connections() {
    local pids=$(get_nuke_pids)

    if [ -z "$pids" ]; then
        log_info "No Nuke processes running"
        return 0
    fi

    log_info "Monitoring Nuke processes: $(echo $pids | tr '\n' ' ')"

    local found_external=false

    # Check each Nuke PID
    for pid in $pids; do
        # Get process name and command
        local proc_info=$(ps -p "$pid" -o comm,cmd --no-headers 2>/dev/null)

        if [ -z "$proc_info" ]; then
            # Process may have exited
            continue
        fi

        # Get established connections (exclude localhost)
        local connections=$(sudo ss -tnp 2>/dev/null | grep "pid=$pid" | grep "ESTAB" | grep -v "127.0.0.1")

        if [ -n "$connections" ]; then
            # Parse connections
            while IFS= read -r conn; do
                # Extract remote IP and port
                # ss output format: ESTAB 0 0 local_ip:port remote_ip:port
                local remote=$(echo "$conn" | awk '{print $5}')
                local remote_ip=$(echo "$remote" | cut -d':' -f1)
                local remote_port=$(echo "$remote" | cut -d':' -f2)

                # Skip if localhost or local network (adjust if needed)
                if [[ "$remote_ip" == 127.* ]] || [[ "$remote_ip" == 10.* ]] || [[ "$remote_ip" == 192.168.* ]]; then
                    continue
                fi

                found_external=true

                # Resolve domain
                local domain=$(resolve_ip_to_domain "$remote_ip")

                # Create detailed alert
                local alert_msg="Nuke external connection detected"
                alert_msg+="\n  Process: $proc_info"
                alert_msg+="\n  PID: $pid"
                alert_msg+="\n  Remote: $remote_ip:$remote_port"
                alert_msg+="\n  Domain: $domain"
                alert_msg+="\n  Full connection: $conn"

                log_alert "$alert_msg"

                # Check if it's a known Foundry endpoint
                if [ "$domain" != "unknown" ] && [[ "$domain" =~ foundry|honeycomb|sentry ]]; then
                    log_alert "⚠ Known telemetry endpoint: $domain"
                fi

            done <<< "$connections"
        fi
    done

    if [ "$found_external" = false ]; then
        log_success "No external connections detected (localhost only)"
    fi

    return 0
}

run_continuous() {
    log_info "Starting continuous monitoring (interval: ${CHECK_INTERVAL}s)"
    log_info "Press Ctrl+C to stop"
    log_info "Alerts will be logged to: $ALERT_LOG"
    echo ""

    # Create alert log if it doesn't exist
    touch "$ALERT_LOG"

    while true; do
        check_nuke_connections
        echo ""
        sleep "$CHECK_INTERVAL"
    done
}

run_daemon() {
    log_info "Starting daemon mode (background)"

    # Redirect output to log
    DAEMON_LOG="/tmp/nuke_monitor_daemon.log"

    # Run in background
    nohup bash "$0" --continuous > "$DAEMON_LOG" 2>&1 &

    local daemon_pid=$!

    log_success "Daemon started (PID: $daemon_pid)"
    log_info "Daemon log: $DAEMON_LOG"
    log_info "Alert log: $ALERT_LOG"
    log_info "Stop with: kill $daemon_pid"
}

show_help() {
    cat << EOF
Nuke Network Monitoring and Alert Script

Usage:
  bash monitor_nuke_network.sh              Run one-time check
  bash monitor_nuke_network.sh --continuous Run continuously (Ctrl+C to stop)
  bash monitor_nuke_network.sh --daemon     Run as background daemon
  bash monitor_nuke_network.sh --log        Show alert log
  bash monitor_nuke_network.sh --help       Show this help

Installation as Cron Job:
  # Check every 5 minutes
  crontab -e
  # Add this line:
  */5 * * * * /home/nicholai/Documents/obsidian-vault/2-projects/Nuke-monitoring/scripts/monitor_nuke_network.sh >> /tmp/nuke_monitor.log 2>&1

Installation as Systemd Timer:
  # Create service file: /etc/systemd/system/nuke-monitor.service
  # Create timer file: /etc/systemd/system/nuke-monitor.timer
  # See script comments for full systemd unit files

What This Does:
  - Finds all running Nuke processes
  - Checks for external network connections (non-localhost)
  - Alerts when Foundry telemetry endpoints are contacted
  - Logs alerts to: $ALERT_LOG
  - Sends desktop notifications (if available)

Alert Log: $ALERT_LOG
EOF
}

show_log() {
    if [ ! -f "$ALERT_LOG" ]; then
        log_info "No alerts logged yet"
        log_info "Alert log will be created at: $ALERT_LOG"
        return
    fi

    log_info "Recent alerts (last 20 lines):"
    echo ""
    tail -20 "$ALERT_LOG"
    echo ""
    log_info "Full log: $ALERT_LOG"
}

main() {
    case "$1" in
        --continuous|-c)
            run_continuous
            ;;
        --daemon|-d)
            run_daemon
            ;;
        --log|-l)
            show_log
            ;;
        --help|-h)
            show_help
            ;;
        *)
            # Default: run single check
            check_nuke_connections
            ;;
    esac
}

main "$@"

# Systemd unit files for reference:
#
# /etc/systemd/system/nuke-monitor.service:
# [Unit]
# Description=Nuke Network Monitoring
# After=network.target
#
# [Service]
# Type=simple
# ExecStart=/home/nicholai/Documents/obsidian-vault/2-projects/Nuke-monitoring/scripts/monitor_nuke_network.sh --continuous
# Restart=always
# User=root
#
# [Install]
# WantedBy=multi-user.target
#
# /etc/systemd/system/nuke-monitor.timer:
# [Unit]
# Description=Nuke Network Monitoring Timer
#
# [Timer]
# OnBootSec=1min
# OnUnitActiveSec=5min
#
# [Install]
# WantedBy=timers.target
#
# Enable with:
#   sudo systemctl daemon-reload
#   sudo systemctl enable --now nuke-monitor.timer
