#!/bin/bash

# Incident Response Phase 4: Monitoring & Prevention (Remote Execution)
# Usage: ./phase4.sh <target_host>
# This script runs from operator machine and sets up monitoring remotely via SSH

set -euo pipefail

# Configuration
SCRIPT_VERSION="1.0"
PHASE="phase4-monitoring"
SSH_USER="ir"

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

# Check parameters and setup
if [[ $# -ne 1 ]]; then
    echo -e "${RED}Usage: $0 <target_host>${NC}"
    echo -e "${YELLOW}Example: $0 webserver01.company.com${NC}"
    exit 1
fi

TARGET_HOST="$1"
TIMESTAMP=$(date '+%Y%m%d_%H%M%S')
BASE_DIR="./incident_response"
HOST_DIR="$BASE_DIR/$TARGET_HOST"
PHASE_DIR="$HOST_DIR/$PHASE"
LOG_FILE="$PHASE_DIR/${PHASE}_${TIMESTAMP}.log"
SUMMARY_FILE="$PHASE_DIR/${PHASE}_summary_${TIMESTAMP}.txt"
mkdir -p "$PHASE_DIR"

# Logging functions
log() { echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}" | tee -a "$LOG_FILE"; }
error() { echo -e "${RED}[ERROR] $1${NC}" | tee -a "$LOG_FILE"; exit 1; }
warn() { echo -e "${YELLOW}[WARNING] $1${NC}" | tee -a "$LOG_FILE"; }
info() { echo -e "${BLUE}[INFO] $1${NC}" | tee -a "$LOG_FILE"; }
critical() { echo -e "${RED}[CRITICAL] $1${NC}" | tee -a "$LOG_FILE"; }

# Remote command execution
remote_cmd() {
    local cmd="$1" description="$2" critical_action="$3"
    [[ "$critical_action" == "true" ]] && critical "EXECUTING: $description" || log "Running: $description"
    echo "=== $description ===" >> "$LOG_FILE"
    echo "Target: $TARGET_HOST" >> "$LOG_FILE"
    echo "Command: $cmd" >> "$LOG_FILE"
    echo "Output:" >> "$LOG_FILE"
    if ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "$cmd" >> "$LOG_FILE" 2>&1; then
        [[ "$critical_action" == "true" ]] && critical "✓ $description completed successfully" || info "✓ $description completed"
    else
        warn "✗ $description failed or returned non-zero exit code"
    fi
    echo "" >> "$LOG_FILE"
}

# Test SSH connectivity
log "Testing SSH connectivity to $TARGET_HOST..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "echo 'SSH connection successful'" >/dev/null 2>&1; then
    error "Cannot connect to $TARGET_HOST as $SSH_USER"
fi
info "✓ SSH connection successful"

# Start monitoring setup
log "=== INCIDENT RESPONSE PHASE 4: MONITORING & PREVENTION ==="
log "Target Host: $TARGET_HOST"
log "Operator Machine: $(hostname)"
critical "SETTING UP COMPREHENSIVE MONITORING AND THREAT DETECTION"

# Create remote monitoring directory structure
log "Phase 4.1: Setting up remote monitoring infrastructure"
remote_cmd "mkdir -p /opt/ir_monitor/{baselines,evidence,scripts}" "Create monitoring directories" "true"

# Install monitoring tools
log "Phase 4.2: Installing monitoring tools"
remote_cmd "apt update && apt install -y inotify-tools aide sysstat logrotate" "Install monitoring tools" "false"

# Create system baselines
log "Phase 4.3: Creating system baselines"
remote_cmd "find /etc /var/www /usr/local -type f -exec md5sum {} \\; > /opt/ir_monitor/baselines/file_integrity_baseline_${TIMESTAMP}.md5 2>/dev/null || true" "Create file integrity baseline" "true"
remote_cmd "ps aux > /opt/ir_monitor/baselines/process_baseline_${TIMESTAMP}.txt" "Create process baseline" "false"
remote_cmd "ss -tulpn > /opt/ir_monitor/baselines/network_baseline_${TIMESTAMP}.txt" "Create network baseline" "false"
remote_cmd "systemctl list-unit-files --state=enabled > /opt/ir_monitor/baselines/services_baseline_${TIMESTAMP}.txt" "Create services baseline" "false"
remote_cmd "echo $TIMESTAMP > /opt/ir_monitor/baselines/baseline_timestamp" "Set baseline timestamp" "false"

# Create monitoring scripts on target
log "Phase 4.4: Deploying monitoring scripts"

# Security monitor script
remote_cmd 'cat > /opt/ir_monitor/scripts/security_monitor.sh << '"'"'EOF'"'"'
#!/bin/bash
LOG_FILE="/var/log/security_alerts.log"
echo "$(date): Starting security monitoring sweep" >> $LOG_FILE

# Check for suspicious processes
SUSPICIOUS_PROCS=$(ps aux | grep -E "(nc|netcat|python.*socket|perl.*socket|bash.*tcp)" | grep -v grep | wc -l)
if [[ $SUSPICIOUS_PROCS -gt 0 ]]; then
    echo "$(date): ALERT: Suspicious processes detected" >> $LOG_FILE
    ps aux | grep -E "(nc|netcat|python.*socket|perl.*socket|bash.*tcp)" | grep -v grep >> $LOG_FILE
fi

# Check for backdoor ports
BACKDOOR_PROCS=$(ss -tulpn | grep -E ":(4444|5555|6666|7777|8080|9999|31337)" | wc -l)
if [[ $BACKDOOR_PROCS -gt 0 ]]; then
    echo "$(date): ALERT: Processes listening on backdoor ports" >> $LOG_FILE
    ss -tulpn | grep -E ":(4444|5555|6666|7777|8080|9999|31337)" >> $LOG_FILE
fi

# Check for failed logins
FAILED_LOGINS=$(grep "Failed password" /var/log/auth.log 2>/dev/null | tail -100 | wc -l)
if [[ $FAILED_LOGINS -gt 10 ]]; then
    echo "$(date): WARNING: High number of failed logins: $FAILED_LOGINS" >> $LOG_FILE
fi

# Check for webshells
if [[ -d "/var/www" ]]; then
    WEBSHELLS=$(find /var/www -name "*.php" -exec grep -l "eval\\|base64_decode\\|system\\|shell_exec" {} \\; 2>/dev/null | wc -l)
    if [[ $WEBSHELLS -gt 0 ]]; then
        echo "$(date): ALERT: Potential webshells detected: $WEBSHELLS" >> $LOG_FILE
    fi
fi

# Collect evidence
ps aux > "/opt/ir_monitor/evidence/processes_$(date +%Y%m%d_%H%M).txt"
ss -tulpn > "/opt/ir_monitor/evidence/network_$(date +%Y%m%d_%H%M).txt"
ls -la /tmp > "/opt/ir_monitor/evidence/tmp_files_$(date +%Y%m%d_%H%M).txt"

# Clean old evidence (keep 24 hours)
find /opt/ir_monitor/evidence -type f -mtime +1 -delete 2>/dev/null || true

echo "$(date): Security monitoring sweep completed" >> $LOG_FILE
EOF
chmod +x /opt/ir_monitor/scripts/security_monitor.sh' "Deploy security monitor script" "true"

# Threat hunting script
remote_cmd 'cat > /opt/ir_monitor/scripts/threat_hunt.sh << '"'"'EOF'"'"'
#!/bin/bash
echo "=== THREAT HUNTING REPORT - $(date) ==="
echo "Target: $(hostname)"

echo "=== Checking for IOCs ==="
echo "Potential webshells:"
find /var/www -name "*.php" -exec grep -l "eval\\|base64_decode\\|system" {} \\; 2>/dev/null | head -10

echo "Suspicious processes:"
ps aux | grep -E "(nc|netcat|python.*socket|perl.*socket|bash.*tcp)" | grep -v grep

echo "Backdoor ports:"
ss -tulpn | grep -E ":(4444|5555|6666|7777|8080|9999|31337)"

echo "Recent suspicious files:"
find /tmp /dev/shm /var/tmp -type f -mtime -1 2>/dev/null | head -10

echo "Cron jobs:"
crontab -l 2>/dev/null | grep -v "^#"

echo "=== END THREAT HUNT ==="
EOF
chmod +x /opt/ir_monitor/scripts/threat_hunt.sh' "Deploy threat hunting script" "true"

# Set up cron jobs
log "Phase 4.5: Setting up automated monitoring"
remote_cmd 'echo "*/5 * * * * /opt/ir_monitor/scripts/security_monitor.sh" | crontab -' "Install security monitoring cron job" "true"

# Configure log rotation
remote_cmd 'cat > /etc/logrotate.d/ir_monitoring << EOF
/var/log/security_alerts.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
    create 644 root root
}
EOF' "Configure log rotation" "false"

# Initialize AIDE if available
log "Phase 4.6: Setting up file integrity monitoring"
remote_cmd "command -v aide >/dev/null && (aideinit; mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db 2>/dev/null || true) || echo 'AIDE not available'" "Initialize AIDE" "false"

# Set up real-time web monitoring if web directory exists
remote_cmd "if [[ -d '/var/www/html' ]]; then nohup inotifywait -m /var/www/html -e create,modify,delete --format '%w%f %e %T' --timefmt '%Y-%m-%d %H:%M:%S' --outfile /var/log/realtime_web.log --daemon; echo 'Web monitoring started'; else echo 'No web directory found'; fi" "Start real-time web monitoring" "false"

# Run initial security check
log "Phase 4.7: Running initial security assessment"
remote_cmd "/opt/ir_monitor/scripts/security_monitor.sh" "Run initial security check" "true"

# Copy monitoring status to operator machine
log "Phase 4.8: Copying monitoring status to operator machine"
ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "cat /var/log/security_alerts.log 2>/dev/null | tail -20" > "$PHASE_DIR/initial_security_alerts.txt" 2>/dev/null || true
ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "/opt/ir_monitor/scripts/threat_hunt.sh" > "$PHASE_DIR/initial_threat_hunt.txt" 2>/dev/null || true
ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "ls -la /opt/ir_monitor/baselines/" > "$PHASE_DIR/baselines_created.txt" 2>/dev/null || true

# Generate monitoring summary
{
    echo "=== MONITORING SETUP COMPLETED ==="
    echo "Target Host: $TARGET_HOST"
    echo "Monitoring Directory: /opt/ir_monitor/"
    echo ""
    echo "✓ Monitoring tools installed and configured"
    echo "✓ System baselines created"
    echo "✓ Security monitoring scripts deployed"
    echo "✓ Automated cron jobs scheduled"
    echo "✓ Log rotation configured"
    echo "✓ File integrity monitoring initialized"
    echo "✓ Real-time web monitoring active"
    echo "✓ Initial security assessment completed"
    echo ""
    echo "=== MONITORING COMPONENTS (ON TARGET) ==="
    echo "• Security alerts: /var/log/security_alerts.log"
    echo "• Monitoring scripts: /opt/ir_monitor/scripts/"
    echo "• System baselines: /opt/ir_monitor/baselines/"
    echo "• Evidence collection: /opt/ir_monitor/evidence/"
    echo ""
    echo "=== MONITORING SCHEDULE ==="
    echo "• Security monitor: Every 5 minutes"
    echo "• Evidence collection: Every 5 minutes"
    echo "• Log rotation: Daily"
    echo ""
    echo "=== MANUAL MONITORING COMMANDS (ON TARGET) ==="
    echo "• View security alerts: tail -f /var/log/security_alerts.log"
    echo "• Run threat hunt: /opt/ir_monitor/scripts/threat_hunt.sh"
    echo "• Check security status: /opt/ir_monitor/scripts/security_monitor.sh"
    echo ""
    echo "=== LOCAL FILES GENERATED ==="
    ls -la "$PHASE_DIR" | grep -v "^total"
    echo ""
    echo "=== FINAL STATUS ==="
    echo "All incident response phases completed successfully."
    echo "Target system is now secured and monitored."
    echo "Continue monitoring security alerts and run threat hunting regularly."
} >> "$SUMMARY_FILE"

critical "Phase 4 Monitoring setup completed successfully"
log "Summary file: $SUMMARY_FILE"
log "All monitoring components active on target host"

echo
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  PHASE 4 MONITORING COMPLETE          ${NC}"
echo -e "${GREEN}========================================${NC}"
echo
echo -e "${YELLOW}Target Host:${NC} $TARGET_HOST"
echo -e "${YELLOW}Local Log Directory:${NC} $PHASE_DIR"
echo -e "${GREEN}SUCCESS: Comprehensive monitoring active${NC}"
echo
echo -e "${BLUE}Remote Monitoring Commands:${NC}"
echo -e "${GREEN}ssh $SSH_USER@$TARGET_HOST 'tail -f /var/log/security_alerts.log'${NC}"
echo -e "${GREEN}ssh $SSH_USER@$TARGET_HOST '/opt/ir_monitor/scripts/threat_hunt.sh'${NC}"
echo
echo -e "${BLUE}🎉 ALL INCIDENT RESPONSE PHASES COMPLETE${NC}"
echo -e "${YELLOW}System is secured, recovered, and monitored.${NC}"