#!/usr/bin/env sh
set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PLUGIN_DIR=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)
RUNNER="$SCRIPT_DIR/background-runner.php"

LIMIT=20
COMMAND=run

for arg in "$@"; do
	case "$arg" in
		start|run|stop|status)
			COMMAND="$arg"
			;;
		--limit=*)
			LIMIT=${arg#--limit=}
			;;
	esac
done

WP_ROOT=$(CDPATH= cd -- "$PLUGIN_DIR/../.." && pwd)
DEBUG_DIR="$WP_ROOT/uploads/niwa-debug"
PID_FILE="$DEBUG_DIR/background-chain.pid"
LOG_FILE="$DEBUG_DIR/background-chain.log"

mkdir -p "$DEBUG_DIR"

pid_from_file() {
	if [ -f "$PID_FILE" ]; then
		cat "$PID_FILE" 2>/dev/null || true
	fi
}

pid_cmd() {
	pid="$1"
	ps -p "$pid" -o args= 2>/dev/null || true
}

is_chain_pid() {
	pid="$1"
	cmd=$(pid_cmd "$pid")
	case "$cmd" in
		*background-chain.sh*) return 0 ;;
		*background-runner.php*) return 0 ;;
	esac
	return 1
}

case "$COMMAND" in
	start)
		pid=$(pid_from_file)
		if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null && is_chain_pid "$pid"; then
			echo "already_running pid=$pid"
			exit 0
		fi
		rm -f "$PID_FILE"
		echo "one_shot_start"
		echo "$$" > "$PID_FILE"
		trap 'current=$(pid_from_file); [ "$current" = "$$" ] && rm -f "$PID_FILE" || true' EXIT INT TERM
		printf '[%s] niwa one-shot background runner pid=%s limit=%s source=start\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" "$LIMIT" >> "$LOG_FILE"
		php "$RUNNER" --limit="$LIMIT"
		exit $?
		;;
	stop)
		pid=$(pid_from_file)
		if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null && is_chain_pid "$pid"; then
			kill "$pid" 2>/dev/null || true
			echo "stopped pid=$pid"
		elif [ -n "$pid" ]; then
			echo "stale_pid_not_killed pid=$pid"
		else
			echo "not_running"
		fi
		rm -f "$PID_FILE"
		exit 0
		;;
	status)
		pid=$(pid_from_file)
		if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null && is_chain_pid "$pid"; then
			echo "running pid=$pid"
			exit 0
		fi
		if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
			echo "stale_pid_reused pid=$pid"
			rm -f "$PID_FILE"
			exit 2
		fi
		rm -f "$PID_FILE"
		echo "not_running"
		exit 1
		;;
	run)
		echo "$$" > "$PID_FILE"
		trap 'current=$(pid_from_file); [ "$current" = "$$" ] && rm -f "$PID_FILE" || true' EXIT INT TERM
		printf '[%s] niwa one-shot background runner pid=%s limit=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" "$LIMIT" >> "$LOG_FILE"
		php "$RUNNER" --limit="$LIMIT"
		exit $?
		;;
esac

echo "unknown_command"
exit 1
