#!/bin/sh

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
BIN="$SCRIPT_DIR/bin/darkbot"
PIDFILE="$SCRIPT_DIR/darkbot.pid"
OUTFILE="$SCRIPT_DIR/darkbot.out"
CONNECT_WAIT=20

if [ ! -x "$BIN" ]; then
	echo "darkbot: missing executable: $BIN" >&2
	exit 1
fi

if [ -r "$PIDFILE" ]; then
	PID=$(cat "$PIDFILE")
	if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
		echo "darkbot: already running with pid $PID"
		exit 0
	fi
fi

cd "$SCRIPT_DIR" || exit 1
nohup "$BIN" "$@" >"$OUTFILE" 2>&1 &
PID=$!
printf '%s\n' "$PID" >"$PIDFILE"
echo "darkbot: started pid $PID"

tail -n +1 -f "$OUTFILE" &
TAILPID=$!

WAITED=0
while kill -0 "$PID" 2>/dev/null; do
	if grep -q "Connected to .*!" "$OUTFILE" 2>/dev/null; then
		break
	fi
	if [ "$WAITED" -ge "$CONNECT_WAIT" ]; then
		break
	fi
	sleep 1
	WAITED=$((WAITED + 1))
done

kill "$TAILPID" 2>/dev/null
wait "$TAILPID" 2>/dev/null

if kill -0 "$PID" 2>/dev/null; then
	if grep -q "Connected to .*!" "$OUTFILE" 2>/dev/null; then
		echo "darkbot: connected, running in background"
	else
		echo "darkbot: still connecting, running in background"
	fi
else
	echo "darkbot: exited before connecting; see $OUTFILE" >&2
	exit 1
fi
