#!/bin/sh

prefix=/usr/local
exec_prefix=${prefix}
ETC=/etc/kismet
BIN=${exec_prefix}/bin

GREP_OPTIONS=""

gui=`grep -e "^gui=" ${ETC}/kismet_ui.conf | cut -d= -f2 | tr -d " \t"`
piddir=`grep -e "^piddir=" ${ETC}/kismet.conf | cut -d= -f2 | tr -d " \t"`

if test "$gui" = ""; then
	echo "No gui specified in ${ETC}/kismet_ui.conf.  Please specify one!"
	exit
fi

if test "$piddir" = ""; then
    echo "No piddir specified in ${ETC}/kismet.conf.  Please specify one!"
    exit
fi

mode="server"
while test "$1" != ""; do
	if test "$1" = "-h" -o "$1" = "--help"; then
		echo "$0 [server options] -- [client options]"
		echo "ex: $0 -c pcap,eth0,cisco,Kismet -p 5000 -- -q -p 5000"
		echo "to start the server with a pcap capture source on port 5000 and start the"
		echo "client in quiet mode on the same port."
		exit
	elif test "$1" = "--"; then
		mode="client";
	elif test "$mode" = "server"; then
		server="$server $1"
	elif test "$mode" = "client"; then
		client="$client $1"
	fi

	shift
done

if test "$server" = ""; then
	echo "Server options:  none"
else
	echo "Server options:  $server"
fi

if test "$client" = ""; then
	echo "Client options:  none"
else
	echo "Client options:  $client"
fi

echo "Starting server..."
${BIN}/kismet_server --silent $server &

servpid=$!

echo "Waiting for server to start before starting UI..."
sleep 4

exit_kismet() {
	kill -0 $servpid && echo Killing server... && kill $servpid
	echo Kismet exited.
}

if kill -0 $servpid 2>/dev/null; then
    trap exit_kismet EXIT INT TERM
else
    # Don't print anything here so that users don't get confused,
    # just die and let them read the server fatal errors
    exit 1
fi

echo "Starting UI..."
${BIN}/kismet_client $client
