#!/bin/sh -x
# rename_pcaps.sh
# Renames pcap files in current working directory using file mtime (UTC->PST)
#
# Input glob:    ${FINAL_NAME}-*.pca*
# Output format: ${FINAL_NAME}.YYYY-MM-DD.{HH}{MM}{SS}{seq}.pcap

FINAL_NAME="wrccdc-inv5"
LAST_TIME_BASE=""
LAST_SEQ=0

find . -maxdepth 1 -name "wrccdc-inv4-2025.pca*" -type f | sort -V | \
while read -r INPUT; do
    BASENAME=$(basename "$INPUT")

    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"

    MTIME_REF=$(mktemp)
    touch -r "$INPUT" "$MTIME_REF"

    echo "$BASENAME -> $OUT_NAME"
    mv "$INPUT" "./$OUT_NAME"

    touch -r "$MTIME_REF" "./$OUT_NAME"
    rm -f "$MTIME_REF"
done

echo "Done."

