#!/bin/sh

cd "$AUTOPKGTEST_TMP"

# directory for settings file, logs, and other cruft
DIR="settings"

fresh_ini() {
	mkdir -p "$AUTOPKGTEST_TMP/$DIR" >/dev/null 2>&1 || exit 1
	mktemp -u -p "$AUTOPKGTEST_TMP/$DIR" -t XXXXXXXX.ini
}

cleanup() {
	[ -d "$DIR" ] && rm -vrf "$DIR"
}

mdk() {
	target=$1
	# wait a bit for sabnzbd to complete startup
	sleep 30
	if [ $(kill -0 $target >/dev/null 2>&1; echo $?) -eq 0 ]; then
		# good, target still active
		kill -s TERM $target || kill -s KILL $target
		ret_kill=$?
		sleep 15
		return $ret_kill
	else
		# bad, target process exited early
		sleep 1
		return 1
	fi
}

# display usage info
sabnzbdplus --help --config-file "$(fresh_ini)"
RET=$?
echo "usage info finished, status = $RET"
cleanup

# console run, empty settings file
sabnzbdplus --logging 1 --browser 0 --config-file "$(fresh_ini)" &
pid_sab=$!
# create a second background process, to terminate the first
mdk $pid_sab &
pid_mdk=$!
# ... and wait for both to return
wait $pid_sab
RET=$((RET+$?))
echo "console run finished, status = $RET"
wait $pid_mdk
RET=$((RET+$?))
echo "mdk finished, status = $RET"
cleanup

exit $RET
