#!/bin/sh

file=pcap.
intf=fabric
filter=vlan
EXEC=exec
while test $# -ne 0; do
  option=$1
  shift
  optarg=

  case $option in
      -w)
          file=$1
          shift;;
      -w*)
          file=${1:2}
          ;;
      -i)
          intf=$1
          shift;;
      -i*)
          intf=${1:2}
          shift;;
      -n)
          ECHO="echo";;
      -d)
          EXEC="daemonize";;
      -h|--help)
          echo capture - capture packets received on the network
          echo
          echo "usage: capture [-d] [-n] [-w <filepath>] [-i intf] [expr]"
          echo "       capture -h|--help"
          echo
          echo DESCRIPTION
          echo
          echo capture packets received on the network to a set of 3 rotating
          echo pcap files, named pcap.0, pcap.1, and pcap.2.
          echo The next file is used once a file reaches 1000000 bytes.
          echo Old files are automatically gzip-compressed.
          echo
          echo OPTIONS
          echo
          echo "'expr' is an optional filter expression matching the packets"
          echo "    to be captured, in tcpdump syntax.  If not specified, all"
          echo "    packets are captured."
          echo
          echo "-w: change the file prefix of the output files.  This can"
          echo "    be a relative or absolute file path."
          echo
          echo "-i: specify the interface to capture.  The default interface"
          echo "    is 'fabric'."
          echo
          echo "-n: print the tcpdump command but do not execute it"
          echo 
          echo "-d: daemonize and run the program in the background."
          echo "    When daemonized, the working directory is /."
          exit 0;
          ;;
      *)
          filter="vlan and ( $option $* )"
          break;;
  esac
done

echo "Capturing to $file{0,1,2}"
if [ "$EXEC" == "daemonize" ]; then
    echo Running tcpdump as a daemon
fi
$ECHO $EXEC \
/usr/sbin/tcpdump -Z root -i $intf -UC 1 -W 3 -w $file -z gzip $filter
