#!/bin/sh

if [ $# -lt 2 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
        echo "Usage: `basename $0` <dst index dir> <source pcap dir>"
	echo "or: `basename $0` -f <filelist> <dst index dir>"
        echo "Note: if <dst index dir> does not exist, it will be created."
        exit 1
fi

if [ "$1" == "-f" ]; then
	shift;
	FILELIST=$1
	shift;
fi

TCPDUMP=`which tcpdump 2> /dev/null`
if [ "$TCPDUMP" == "" ]; then
	TCPDUMP=/usr/sbin/tcpdump
fi
if [ ! -x $TCPDUMP ]; then
	echo "ERR: cannot find tcpdump ($TCPDUMP)."
	exit 1
fi

INDEX_DIR="${1%/}"
if [ ! -d "$INDEX_DIR" ]; then
	mkdir -p $INDEX_DIR
fi
ABS_INDEX_DIR=`readlink -e "$INDEX_DIR"`

if [ "$FILELIST" != "" ]; then
	FILES=`cat $FILELIST`
else
	if [ ! -d "$2" ]; then
        	echo "ERR: \"$2\" does ot exist."
	        exit 2
	fi
        PCAP_DIR="${2%/}"
        ABS_PCAP_DIR=`readlink -e "$PCAP_DIR"`
	FILES=`find $ABS_PCAP_DIR -iname "*.pcap*"`
fi

for F in $FILES; do
	echo $F
	echo $F | grep '\.gz$' > /dev/null
	if [ $? = "0" ]; then
		TS=`gunzip -c $F | $TCPDUMP -c 1 -tt -n -r - 2> /dev/null | awk '{print $1}'`
	else
		TS=`$TCPDUMP -c 1 -tt -n -r $F 2> /dev/null | awk '{print $1}'`
	fi
	F=`readlink -e "$F"`
	if [ "$TS" != "" ]; then
		ln -s $F $ABS_INDEX_DIR/$TS
	else
		echo "ERR: cannot extract TS from $F"
	fi
done
