#!/bin/bash -x
# process_pcaps_local.sh

set -e

PCAP_DIR="./"
START_NAME="wrccdc-inv2-2025"
FINAL_NAME="wrccdc-inv3"
FILTER="not (net 10.0.0.0/24 or net 192.168.3.0/24 or net 10.1.0.0/16)"

LAST_TIME_BASE=""
LAST_SEQ=0

find "$PCAP_DIR" -maxdepth 1 -name "${START_NAME}*.pca*" -type f | sort -V | \
while read -r INPUT; do
    BASENAME=$(basename "$INPUT")

    echo "[$(date '+%T')] Processing: $BASENAME"

    EPOCH=$(stat -c '%Y' "$INPUT" 2>/dev/null || stat -f '%m' "$INPUT" 2>/dev/null)
    PST_EPOCH=$((EPOCH - 28800))

    DATE_PART=$(date -u -d "@$PST_EPOCH" '+%Y-%m-%d' 2>/dev/null || date -u -r "$PST_EPOCH" '+%Y-%m-%d')
    TIME_BASE=$(date -u -d "@$PST_EPOCH" '+%H%M%S' 2>/dev/null || date -u -r "$PST_EPOCH" '+%H%M%S')

    if [ "$TIME_BASE" = "$LAST_TIME_BASE" ]; then
        LAST_SEQ=$((LAST_SEQ + 1))
    else
        LAST_SEQ=0
        LAST_TIME_BASE="$TIME_BASE"
    fi
    SEQ=$(printf '%04d' "$LAST_SEQ")

    OUT_NAME="${FINAL_NAME}.${DATE_PART}.${TIME_BASE}${SEQ}.pcap"
    OUTPUT="$PCAP_DIR/$OUT_NAME"

    # --- Filter the pcap ---
    if tcpdump -Z root -r "$INPUT" -w "$OUTPUT" "$FILTER"; then
        echo "[$(date '+%T')] Filtered OK -> $OUT_NAME"
    else
        echo "[ERROR] tcpdump failed on $BASENAME" >&2
        rm -f "$OUTPUT"
        continue
    fi

    touch -r "$INPUT" "$OUTPUT"
    #rm -f "$INPUT"
done

echo ""
echo "========================================="
echo "All pcaps processed."
echo "========================================="
