#!/usr/bin/env bash
# Linux incident evidence collection script.
# Collects volatile data first (memory, network, processes), then persistent.
# Usage: sudo bash scripts/collect_evidence.sh [--output-dir /path/to/evidence]
set -euo pipefail

OUTPUT_DIR="${1:-/tmp/ir-evidence-$(date +%Y%m%d-%H%M%S)}"
mkdir -p "$OUTPUT_DIR"

echo "=== Incident Evidence Collection ==="
echo "Output: $OUTPUT_DIR"
echo "Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo ""

# Order: volatile → persistent (RFC 3227)

echo "--- 1. Network Connections (volatile) ---"
ss -tulnp > "$OUTPUT_DIR/network-connections.txt" 2>&1
netstat -an >> "$OUTPUT_DIR/network-connections.txt" 2>/dev/null || true
echo "  ✅ Saved"

echo "--- 2. Running Processes (volatile) ---"
ps auxf > "$OUTPUT_DIR/processes.txt" 2>&1
echo "  ✅ Saved"

echo "--- 3. Open Files (volatile) ---"
lsof -nP > "$OUTPUT_DIR/open-files.txt" 2>&1 || true
echo "  ✅ Saved"

echo "--- 4. Logged-in Users ---"
w > "$OUTPUT_DIR/logged-users.txt" 2>&1
last -25 >> "$OUTPUT_DIR/logged-users.txt" 2>&1
echo "  ✅ Saved"

echo "--- 5. Network Interfaces ---"
ip addr > "$OUTPUT_DIR/interfaces.txt" 2>&1
ip route >> "$OUTPUT_DIR/interfaces.txt" 2>&1
arp -a >> "$OUTPUT_DIR/interfaces.txt" 2>/dev/null || true
echo "  ✅ Saved"

echo "--- 6. Scheduled Tasks ---"
crontab -l > "$OUTPUT_DIR/crontab-root.txt" 2>&1 || echo "no crontab" > "$OUTPUT_DIR/crontab-root.txt"
ls -la /etc/cron.* >> "$OUTPUT_DIR/crontab-root.txt" 2>&1 || true
for user_dir in /home/*/; do
  user=$(basename "$user_dir")
  crontab -u "$user" -l > "$OUTPUT_DIR/crontab-${user}.txt" 2>/dev/null || true
done
echo "  ✅ Saved"

echo "--- 7. Recent File Modifications ---"
find / -mtime -1 -type f -not -path "/proc/*" -not -path "/sys/*" -not -path "/dev/*" 2>/dev/null | head -200 > "$OUTPUT_DIR/recent-files.txt"
echo "  ✅ Saved"

echo "--- 8. Authentication Logs ---"
cp /var/log/auth.log "$OUTPUT_DIR/auth.log" 2>/dev/null || true
cp /var/log/secure "$OUTPUT_DIR/secure.log" 2>/dev/null || true
journalctl -u sshd --since "24 hours ago" > "$OUTPUT_DIR/sshd-journal.txt" 2>/dev/null || true
echo "  ✅ Saved"

echo "--- 9. System Info ---"
uname -a > "$OUTPUT_DIR/system-info.txt"
cat /etc/os-release >> "$OUTPUT_DIR/system-info.txt" 2>/dev/null || true
uptime >> "$OUTPUT_DIR/system-info.txt"
df -h >> "$OUTPUT_DIR/system-info.txt"
echo "  ✅ Saved"

echo "--- 10. Hash Manifest ---"
find "$OUTPUT_DIR" -type f -not -name "manifest.sha256" -exec sha256sum {} \; > "$OUTPUT_DIR/manifest.sha256"
echo "  ✅ Saved"

echo ""
echo "=== Collection Complete ==="
echo "Files: $(find "$OUTPUT_DIR" -type f | wc -l)"
echo "Total size: $(du -sh "$OUTPUT_DIR" | cut -f1)"
echo "Manifest: $OUTPUT_DIR/manifest.sha256"
