#!/usr/bin/env bash

[ "$1" ] || {
	echo "usage: `basename $0` (start|stop|status|restart|new|clean)..."
	exit 1
}

readonly BIN=piedock

if [ -d src ]
then
	CMD="src/$BIN -r sh/dbgrc"
elif [ -d ../sh ]
then
	CMD="./$BIN -r ../sh/dbgrc"
else
	echo "run this script either from inside src or from the project root"
	exit 1
fi

each()
{
	[ "$1" ] || return

	ps ax | grep "$CMD" | grep -v grep | while read PID REST
	do
		$1 $PID
	done
}

stop()
{
	each "kill"
}

start()
{
	[ -x "${CMD%% *}" ] || build

	$CMD
}

build()
{
	[ -f Makefile ] || ./configure || return 1

	make
}

for ARG in $@
do
	case $ARG in
		star*|ru*)
			start
			;;
		sto*)
			stop
			;;
		stat*)
			each "echo"
			;;
		res*)
			stop
			start
			;;
		c*)
			make clean
			;;
		new|a*)
			stop
			[ $ARG == "anew" ] && make clean
			build || exit 1
			start
			;;
		*)
			echo "unknown argument \"$ARG\""
			exit 1
			;;
	esac
done
