#!/bin/bash
#
# Capture network packets for later replay on dev machines
#
# This should be run as root via a service.
#

OUTDIR="$(realpath "$(dirname "$0")/..")/var/pcap"
OUTNAME="capture-$(hostname)-$(date -u +%s)-$$-pcap"
OUTPATH="$OUTDIR/$OUTNAME"

# Inputs:
#
#  4461/UDP: GPS NMEA
#  4462/UDP: AIS NMEA
# 30000/UDP: Navigation system headers
# Not all inputs will be present in all systems.
#
# NOTE: $INS_HOST must be defined and point to the
# navigation server. The reason we don't use a port
# filter for this data is because that doesn't work
# with fragmented UDP packets.
#
EXPR="udp and (port 4461 or port 4462 or src host $INS_HOST)"

if [[ ! -d "$OUTDIR" ]]; then
    mkdir "$OUTDIR"
fi

# The size of each capture file is 50 MB (-C 50)
# and it will use a ring of 1000 files (-W 1000).
# The capture packet size is unlimited (-s 0).
#
# 50 MB (47.7 MiB) is about one day's worth of data
# so in theory it shouldn't overwrite files even if
# it was running continuously for over two years.
# NOTE: The above figures do not include AIS data.

echo "Logging to: $OUTPATH"
echo "Expression: $EXPR"

tcpdump -i any -n -s 0 -W 1000 -C 50 -w "$OUTPATH" "$EXPR"
