#!/bin/bash
#
# Rewrite packet captures in order to be able to replay them.
#
# SINET:  Rewrite all packets with this source IP address
# SETHER: Rewrite all packets with this MAC
#
# DINET:  Rewrite all packets with this destination IP address
# DETHER: Rewrite all packets with this destination MAC address
#
# The resulting files have the original name with "-rewritten.pcap"
# appended as a suffix. Those packets may then be replayed from a
# different computer or virtual container, for instance with:
#
# sudo bittwist -i 1 -v -m10 capture-rewritten.pcap
#
# Where -i n is the interface name (use bittwist -d to list available
# interfaces), -v is the verbose flag and -m10 replays at 10× speed.
#

SINET=${SINET:-$(ip -o -4 addr |grep -v " lo " |head -n 1 |sed -r 's/^.*inet\s([0-9.]+).*$/\1/')}
SETHER=${SETHER:-$(ip -o link |grep -v " lo" |head -n 1 |sed -r 's/^.*ether\s([0-9a-fA-F:]+).*$/\1/')}

DINET=${DINET:-$(ip -o -4 addr |grep -v " lo " |head -n 1 |sed -r 's/^.*inet\s([0-9.]+).*$/\1/')}
DETHER=${DETHER:-$(ip -o link |grep -v " lo" |head -n 1 |sed -r 's/^.*ether\s([0-9a-fA-F:]+).*$/\1/')}

for f in $*; do

    OUTFNAME=$f-rewritten.pcap
    echo $f → $OUTFNAME
    if [[ -n "$SINET" && -n "$SETHER" ]]; then
        tcprewrite -S 0.0.0.0/0:$SINET --enet-smac=$SETHER \
        -D 0.0.0.0/0:$DINET --enet-dmac=$DETHER \
        --infile "$f" \
        --outfile "$OUTFNAME"
    else
        tcprewrite  -D 0.0.0.0/0:$DINET --enet-dmac=$DETHER \
        --infile "$f" \
        --outfile "$OUTFNAME"
    fi

done
