#!/usr/bin/env bash
# ==============================================================================
# DogWatch Sentinel Ultimate: Sovereign Zero-Overhead Supervisor & Security Shield
# Enterprise & Multi-Node VPS Edition
# Protected by $FREYDOG & Julie Autonomous Security Fleet
# ==============================================================================

set -euo pipefail

PORT="${1:-34180}"
APP_CMD="${2:-python3 /home/nixos/x402_server.py}"
WATCH_DIR="${3:-/home/nixos}"

echo "========================================================================"
echo "🐕 Deploying DogWatch Sentinel Ultimate"
echo "• Monitored Service Port: ${PORT}"
echo "• Supervised Command:     ${APP_CMD}"
echo "• Integrity Scope:        ${WATCH_DIR}"
echo "========================================================================"

# Create the Enterprise DogWatch Daemon
# Use /usr/local/bin if root/sudo available, otherwise fallback to $HOME/.local/bin
INSTALL_DIR="/usr/local/bin"
LOG_DIR="/var/log"
STATE_DIR="/var/lib/dogwatch"

if [ "$(id -u)" -ne 0 ]; then
    if sudo -n true 2>/dev/null; then
        SUDO_PREFIX="sudo"
    else
        INSTALL_DIR="${HOME}/.local/bin"
        LOG_DIR="${HOME}/.dogwatch/logs"
        STATE_DIR="${HOME}/.dogwatch/state"
        SUDO_PREFIX=""
        mkdir -p "$INSTALL_DIR" "$LOG_DIR" "$STATE_DIR"
    fi
else
    SUDO_PREFIX=""
fi

DAEMON_SCRIPT="${INSTALL_DIR}/dogwatch_daemon.sh"
LOG_FILE="${LOG_DIR}/dogwatch.log"

$SUDO_PREFIX mkdir -p "$(dirname "$DAEMON_SCRIPT")" "$STATE_DIR" "$(dirname "$LOG_FILE")"
$SUDO_PREFIX touch "$LOG_FILE" || touch "${HOME}/dogwatch.log"

cat << 'EOF' | $SUDO_PREFIX tee "$DAEMON_SCRIPT" > /dev/null
#!/usr/bin/env bash
set -euo pipefail

PORT="${1:-34180}"
CMD="${2:-python3 /home/nixos/x402_server.py}"
WATCH_DIR="${3:-/home/nixos}"
LOCKFILE="/tmp/dogwatch_${PORT}.lock"
LOG="/var/log/dogwatch.log"
HEALTH_URL="http://127.0.0.1:${PORT}/"
STATE_DIR="/var/lib/dogwatch"
FIM_DB="${STATE_DIR}/fim_hashes.sha256"

mkdir -p "$STATE_DIR"
touch "$LOG"

# 1. Non-blocking Lock (Prevents concurrent/overlapping executions)
exec 200>"$LOCKFILE"
flock -n 200 || exit 0

timestamp() {
    date -u '+%Y-%m-%d %H:%M:%S UTC'
}

# ------------------------------------------------------------------------------
# MODULE 1: AUTOMATED LOG ROTATION & DISK SHIELD (Caps files at 5MB)
# ------------------------------------------------------------------------------
MAX_LOG_BYTES=$((5 * 1024 * 1024))
for logfile in /var/log/dogwatch.log /home/nixos/*.log; do
    [ -f "$logfile" ] || continue
    filesize=$(stat -c%s "$logfile" 2>/dev/null || stat -f%z "$logfile" 2>/dev/null || echo 0)
    if [ "$filesize" -gt "$MAX_LOG_BYTES" ]; then
        tail -n 5000 "$logfile" > "${logfile}.tmp" 2>/dev/null || true
        mv -f "${logfile}.tmp" "$logfile" 2>/dev/null || true
    fi
done

# ------------------------------------------------------------------------------
# MODULE 2: FILE INTEGRITY MONITORING (FIM) & TAMPER DETECTION
# ------------------------------------------------------------------------------
# Generates baseline SHA-256 hashes of critical executable code on first run
# Detects unauthorized script modification, backdoors, or injected payloads
if [ ! -f "$FIM_DB" ]; then
    echo "[$(timestamp)] 🛡️ [FIM] Initializing cryptographic baseline hashes..." >> "$LOG"
    find "$WATCH_DIR" -maxdepth 2 -type f \( -name "*.py" -o -name "*.sh" -o -name "*.json" \) \
        ! -name "*metrics*" ! -name "*log*" ! -name "*.tmp" -exec sha256sum {} + > "$FIM_DB" 2>/dev/null || true
else
    # Check for modifications against the established baseline
    TAMPERED_FILES=$(sha256sum -c "$FIM_DB" 2>/dev/null | grep -E "FAILED|WARNING" || true)
    if [ -n "$TAMPERED_FILES" ]; then
        echo "[$(timestamp)] 🚨 [FIM ALERT] Cryptographic mismatch detected in integrity scope!" >> "$LOG"
        echo "$TAMPERED_FILES" >> "$LOG"
    fi
fi

# ------------------------------------------------------------------------------
# MODULE 3: ROGUE PROCESS & CPU CRYPTO-MINER SENTRY
# ------------------------------------------------------------------------------
# Scans for unauthorized high-load processes, known miner binaries, or reverse shells
ROGUE_PROCESSES=$(ps -eo pid,pcpu,comm,args --sort=-pcpu | awk 'NR>1 {
    # Check for excessive CPU usage by unknown binaries (>90% CPU for non-python/non-system)
    if ($2 > 90.0 && $3 !~ /python|node|caddy|sshd|bash|systemd/) {
        print $1, $2, $3, $4
    }
    # Check for signature keywords associated with unauthorized miners or shells
    if ($4 ~ /xmrig|minerd|stratum\+tcp|nc -e|\/bin\/sh -i/) {
        print "CRITICAL_THREAT:", $1, $3, $4
    }
}')

if [ -n "$ROGUE_PROCESSES" ]; then
    echo "[$(timestamp)] ⚠️ [PROCESS SENTRY ALERT] Suspicious process signature detected:" >> "$LOG"
    echo "$ROGUE_PROCESSES" >> "$LOG"
fi

# ------------------------------------------------------------------------------
# MODULE 4: WEB3 WALLET DRAINER & MALICIOUS EGRESS DEFENSE
# ------------------------------------------------------------------------------
# Inspects active outbound network sockets for unverified high-risk external connections
# Ensures no background tasks are establishing raw socket tunnels to unauthorized ports
SUSPICIOUS_EGRESS=$(ss -tnp 2>/dev/null | awk '$1=="ESTAB" {
    # Extract destination port
    split($5, dst, ":");
    port = dst[length(dst)];
    # Flag unauthorized high-risk peer ports (IRC botnets, common reverse shell ports)
    if (port == 4444 || port == 6667 || port == 1337 || port == 3333 || port == 9999) {
        print $0;
    }
}')

if [ -n "$SUSPICIOUS_EGRESS" ]; then
    echo "[$(timestamp)] 🚨 [EGRESS SENTRY ALERT] High-risk outbound socket detected:" >> "$LOG"
    echo "$SUSPICIOUS_EGRESS" >> "$LOG"
fi

# ------------------------------------------------------------------------------
# MODULE 5: TWO-STAGE SELF-HEALING SUPERVISOR
# ------------------------------------------------------------------------------
is_healthy() {
    if ss -tln | grep -q ":${PORT} "; then
        if curl -s -f -m 8 "$HEALTH_URL" > /dev/null 2>&1; then
            return 0
        fi
        sleep 3
        if curl -s -f -m 8 "$HEALTH_URL" > /dev/null 2>&1; then
            return 0
        fi
    fi
    return 1
}

if is_healthy; then
    exit 0
fi

echo "[$(timestamp)] ⚠️ Monitored service on port ${PORT} unresponsive! Executing self-heal..." >> "$LOG"

# Graceful termination attempt
pkill -TERM -f "$CMD" 2>/dev/null || true
sleep 2.5

# Force termination if hanging
if pgrep -f "$CMD" > /dev/null 2>&1; then
    pkill -KILL -f "$CMD" 2>/dev/null || true
    sleep 1.5
fi

# Revive inside isolated tmux session
tmux new-session -d -s "dogwatch_${PORT}" "$CMD >> $LOG 2>&1"
sleep 3.5

if is_healthy; then
    echo "[$(timestamp)] ✅ Service successfully revived on port ${PORT}!" >> "$LOG"
else
    echo "[$(timestamp)] ❌ Revive failed. Diagnostics written to ${LOG}" >> "$LOG"
fi
EOF

$SUDO_PREFIX chmod +x "$DAEMON_SCRIPT"

# Register cron heartbeat every 5 minutes and on reboot
CRON_JOB="*/5 * * * * ${DAEMON_SCRIPT} '${PORT}' '${APP_CMD}' '${WATCH_DIR}' >/dev/null 2>&1"
REBOOT_JOB="@reboot sleep 15 && ${DAEMON_SCRIPT} '${PORT}' '${APP_CMD}' '${WATCH_DIR}' >/dev/null 2>&1"

(crontab -l 2>/dev/null | grep -v "dogwatch_daemon.sh"; echo "$CRON_JOB"; echo "$REBOOT_JOB") | crontab -

echo "========================================================================"
echo "✅ DogWatch Sentinel Ultimate Successfully Installed & Operational!"
echo "• [Module 1] Automated 5MB log rotation & disk space protection"
echo "• [Module 2] SHA-256 File Integrity Monitoring (FIM) & anti-tamper sentry"
echo "• [Module 3] Rogue process & crypto-miner threat detector"
echo "• [Module 4] Web3 wallet drainer & high-risk egress socket defense"
echo "• [Module 5] Two-stage zero-downtime self-healing supervisor"
echo "========================================================================"
