#!/bin/bash

# Without arguments udp packets or packets for ports 3215 to 3220 will be captured
# You can specify your own filter on commandline.
# Beware: No syntax check for your filter

#We always want to use -s.
# Don't remove getopt (due to compatibility)

SNAPLEN="-s 0"

TEMP=`getopt -o sh -n 'startcapture' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true;do
    case "$1" in
        -h) echo "Usage: startcapture [-s] [filter]"
            echo "                    -s   set snaplen to 65535"
            shift
            exit 0
            ;;
        -s) SNAPLEN="-s 0"
            shift
            ;;
        --) shift
            break
            ;;
        *) echo "Internal error!"
           exit 1
           ;;
    esac    
done
iface=$1
if [ -z "${iface}" ]; then
	iface=eth0
fi

#echo "Remaining arguments:"
#for arg do echo '--> '"\`$arg'" ; done
OWNFILTER="$@"
# Get my MAC addr
mymacaddr=$(ifconfig ${iface} | head -1 | sed -e 's/^.*HWaddr *\([A-Fa-f0-9:]*\).*$/\1/')

#FILTER="ether host $mymacaddr and ( portrange 3215-3229 or portrange 5060-5069 or udp ) and port not 514"
FILTER=" ether host $mymacaddr and not port 514 and not port 22"

#Perhaps user wants his own filter
if [ ! -z "${OWNFILTER}" ] ; then
    FILTER="${OWNFILTER}"
    FILTER=$(echo $FILTER | sed -e "s/%MAC/${mymacaddr}/g")
fi

nohup tcpdump -p -n -i ${iface} -w /data/capture.cap ${SNAPLEN} "${FILTER}" < /dev/null >/dev/null 2>/dev/null &
