#!/bin/bash

usage() {
    cat >&2 <<EOF
$0: reanonymize ERF/PCAP traces using a different key
Usage:
    $0 [-p|v|h] [<input_anon>:]<key1> [<output_anon>:]<key2>

    Reads an ERF/PCAP file from stdin which has already been anonymized
    (e.g. by dag_scrubber) using <key1>.
    Writes to stdout an ERF file with IP addresses reanonymized
    using <key2>.

    OPTIONS:
     -p : by default ERF files for input/output are assumed.  This can be 
          overridden with '-p' option which forces PCAP interpetation for 
          input/output.  
     -v : verbose mode
     -h : this help

    <input_anon>  can be either host or full (defaults to host).
    <output_anon> can be either host or full (defaults to full).
    
Examples:
    $0 key_host-5813 key_host-1234 <20090501-161652-003919-h5813 >20090501-161652-003919-h1234
    $0 key_host-5813 full:key_full-0000 <20090501-161652-003919-h5813 >20090501-161652-003919-f0000
    $0 -p key_host-5813 key_host-1234 <20090501-161652-003919-h5813.pcap >20090501-161652-003919-h1234.pcap
EOF
}

pcap_opts=""
while getopts "hpv" opt; do
    case "$opt" in
	( h ) usage; exit 0; ;;
	( p ) pcap_opts="-P"; ;;
	( v ) verbose="yes"; ;;
	( * ) echo "unknown option $1" >&2; usage; exit 1; ;;
    esac
done
shift $((OPTIND-1))

[ "$#" != "2" ] && { usage; exit 1; }
    
inp=$1
out=$2

DAG_SCRUBBER=dag_scrubber

inp_type=${inp%:*}
inp_keyf=${inp#*:}
inp_opts=""
if [ "$inp_type:$inp_keyf" != "$inp" ]; then
    inp_type="host" #default
fi
case $inp_type in
    ( "host" ) inp_opts="-r -m -s $inp_keyf --pass4=24 --pass6=112" ;;
    ( "full" ) inp_opts="-r -s $inp_keyf" ;;
    ( * ) echo "Error: input_anon must be either host or full" >&2; exit 1; ;;
esac

out_type=${out%:*}
out_keyf=${out#*:}
out_opts=""
if [ "$out_type:$out_keyf" != "$out" ]; then
    out_type="host" #default
fi
case $out_type in
    ( "host" ) out_opts="-m -s $out_keyf --pass4=24 --pass6=112" ;;
    ( "full" ) out_opts="-s $out_keyf" ;;
    ( * ) echo "Error: output_anon must be either host or full" >&2; exit 1; ;;
esac

[ -z "$verbose" ] &&  exec 2>/dev/null

set -o pipefail
if $DAG_SCRUBBER $inp_opts $pcap_opts | $DAG_SCRUBBER $out_opts $pcap_opts; then
    exit 0
else
    echo "Error: reanonymization failed"
    exit 1
fi
