#!/bin/bash
# Automated gap testing for Nuke telemetry
# Handles common issues and provides clear output

OUTPUT_DIR="$HOME/Documents/obsidian-vault/2-projects/Nuke-monitoring/dump/gap-tests"
mkdir -p "$OUTPUT_DIR"
TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)

echo "=== Nuke Telemetry Gap Testing ==="
echo "Output directory: $OUTPUT_DIR"
echo ""

# Check if Nuke is running
NUKE_PID=$(pgrep -f Nuke)
if [ -z "$NUKE_PID" ]; then
    echo "WARNING: Nuke is not currently running."
    echo "Some tests require Nuke to be running."
    echo ""
fi

# Test 1: Inspect local databases
echo "======================================"
echo "TEST 1: Local Database Inspection"
echo "======================================"
echo ""

echo "Finding database files..."
find ~/Documents/nuke ~/.nuke ~/.cache -name "*.db" -o -name "*.sqlite" 2>/dev/null | tee "$OUTPUT_DIR/databases_found.txt"

SYNC_DB="$HOME/.nuke/.sync_8178bafde38a.db"
if [ -f "$SYNC_DB" ]; then
    echo ""
    echo "Analyzing sync database: $SYNC_DB"
    echo "Size: $(du -h "$SYNC_DB" | cut -f1)"
    echo "Type: $(file "$SYNC_DB")"

    # Try to read as SQLite
    if command -v sqlite3 &> /dev/null; then
        echo ""
        echo "SQLite tables:"
        sqlite3 "$SYNC_DB" ".tables" 2>&1 | tee "$OUTPUT_DIR/sqlite_tables.txt"

        echo ""
        echo "SQLite schema (first 50 lines):"
        sqlite3 "$SYNC_DB" ".schema" 2>&1 | head -50 | tee "$OUTPUT_DIR/sqlite_schema.txt"
    else
        echo "sqlite3 not installed. Extracting readable strings..."
        strings "$SYNC_DB" | head -100 > "$OUTPUT_DIR/sync_db_strings.txt"
        echo "Strings saved to: $OUTPUT_DIR/sync_db_strings.txt"
    fi

    # Check for sensitive data
    echo ""
    echo "Checking for sensitive data patterns..."
    strings "$SYNC_DB" | /bin/grep -iE 'email|domain|location|honeycomb|sentry|foundry' | head -20 | tee "$OUTPUT_DIR/sensitive_patterns.txt"
fi

echo ""
echo "Test 1 complete. Results saved to $OUTPUT_DIR/"
echo ""
read -p "Press Enter to continue to Test 2..."

# Test 2: System file access tracing (if Nuke is running)
echo ""
echo "======================================"
echo "TEST 2: System File Access Tracing"
echo "======================================"
echo ""

if [ -z "$NUKE_PID" ]; then
    echo "SKIPPED: Nuke is not running"
else
    echo "Tracing Nuke process: $NUKE_PID"
    echo "This will run for 30 seconds..."
    echo ""

    # Run strace in background
    sudo strace -e trace=open,openat,read -p "$NUKE_PID" -o "$OUTPUT_DIR/strace_raw_$TIMESTAMP.log" 2>&1 &
    STRACE_PID=$!

    echo "strace running (PID: $STRACE_PID)..."
    echo "Please use Nuke normally for the next 30 seconds"
    echo "(Open files, use tools, access menus, etc.)"

    sleep 30

    echo ""
    echo "Stopping strace..."
    sudo kill $STRACE_PID 2>/dev/null
    wait $STRACE_PID 2>/dev/null

    echo "Processing strace output..."

    # Filter for system file access
    /bin/grep -E '/proc|/sys|/etc' "$OUTPUT_DIR/strace_raw_$TIMESTAMP.log" > "$OUTPUT_DIR/system_file_access_$TIMESTAMP.txt" 2>/dev/null

    # Count accesses
    PROC_COUNT=$(/bin/grep -c '/proc' "$OUTPUT_DIR/system_file_access_$TIMESTAMP.txt" 2>/dev/null || echo "0")
    SYS_COUNT=$(/bin/grep -c '/sys' "$OUTPUT_DIR/system_file_access_$TIMESTAMP.txt" 2>/dev/null || echo "0")
    ETC_COUNT=$(/bin/grep -c '/etc' "$OUTPUT_DIR/system_file_access_$TIMESTAMP.txt" 2>/dev/null || echo "0")

    echo ""
    echo "System file accesses found:"
    echo "  /proc: $PROC_COUNT"
    echo "  /sys: $SYS_COUNT"
    echo "  /etc: $ETC_COUNT"
    echo ""
    echo "Sample accesses:"
    head -20 "$OUTPUT_DIR/system_file_access_$TIMESTAMP.txt"
    echo ""
    echo "Full results: $OUTPUT_DIR/system_file_access_$TIMESTAMP.txt"
fi

echo ""
echo "Test 2 complete."
echo ""
read -p "Press Enter to continue to Test 3..."

# Test 3: Startup capture instructions
echo ""
echo "======================================"
echo "TEST 3: Startup Telemetry Capture"
echo "======================================"
echo ""

if [ -n "$NUKE_PID" ]; then
    echo "Nuke is currently running. For this test, you need to:"
    echo "  1. Close Nuke completely"
    echo "  2. Run this script again"
    echo "  OR"
    echo "  3. Manually run the startup capture (see below)"
    echo ""
fi

echo "To manually capture startup telemetry:"
echo ""
echo "1. Close Nuke completely"
echo ""
echo "2. Start packet capture:"
echo "   sudo tcpdump -i any -w $OUTPUT_DIR/startup_$TIMESTAMP.pcap 'host honeycomb.io or host foundry.com or host sentry.foundry.com' &"
echo ""
echo "3. Note the tcpdump PID, then launch Nuke"
echo ""
echo "4. After Nuke fully loads, stop tcpdump:"
echo "   sudo kill <tcpdump_pid>"
echo ""
echo "5. Analyze the capture:"
echo "   tshark -r $OUTPUT_DIR/startup_$TIMESTAMP.pcap -q -z io,stat,0"
echo ""

if [ -z "$NUKE_PID" ]; then
    read -p "Nuke is not running. Do you want to run startup capture now? (y/n): " DO_STARTUP

    if [ "$DO_STARTUP" = "y" ]; then
        echo ""
        echo "Starting packet capture..."
        sudo tcpdump -i any -w "$OUTPUT_DIR/startup_$TIMESTAMP.pcap" 'host honeycomb.io or host foundry.com or host sentry.foundry.com' &
        TCPDUMP_PID=$!

        echo "Packet capture running (PID: $TCPDUMP_PID)"
        echo ""
        echo "NOW LAUNCH NUKE"
        echo ""
        read -p "Press Enter after Nuke has fully loaded..."

        echo ""
        echo "Stopping packet capture..."
        sudo kill $TCPDUMP_PID 2>/dev/null
        wait $TCPDUMP_PID 2>/dev/null

        sleep 2

        if [ -f "$OUTPUT_DIR/startup_$TIMESTAMP.pcap" ]; then
            echo ""
            echo "Capture complete! Analyzing..."

            if command -v tshark &> /dev/null; then
                tshark -r "$OUTPUT_DIR/startup_$TIMESTAMP.pcap" -q -z io,stat,0
                echo ""
                echo "Connections found:"
                tshark -r "$OUTPUT_DIR/startup_$TIMESTAMP.pcap" -T fields -e ip.dst | sort -u
            else
                echo "tshark not installed. Capture saved to:"
                echo "$OUTPUT_DIR/startup_$TIMESTAMP.pcap"
                ls -lh "$OUTPUT_DIR/startup_$TIMESTAMP.pcap"
            fi
        else
            echo "WARNING: Capture file not created. Check sudo permissions."
        fi
    fi
fi

echo ""
echo "======================================"
echo "TESTING COMPLETE"
echo "======================================"
echo ""
echo "Results saved to: $OUTPUT_DIR/"
echo ""
echo "Summary of findings:"
echo "  - Database files: $OUTPUT_DIR/databases_found.txt"
if [ -n "$NUKE_PID" ]; then
    echo "  - System access: $OUTPUT_DIR/system_file_access_$TIMESTAMP.txt"
fi
echo ""
echo "Next steps:"
echo "  1. Review the output files in $OUTPUT_DIR/"
echo "  2. If you haven't done startup capture, close Nuke and run this script again"
echo "  3. Consider running shutdown capture manually (see monitoring-gaps-analysis.md)"
echo ""
