#!/usr/bin/env bash
# A stand-in for dockhand, for the harm sweep's self-test: it answers
# from files in FAKE_DH_STATE, so a self-test row can make each invariant
# break on purpose.
state=${FAKE_DH_STATE:?}
json=0
args=()
for arg in "$@"; do
	case "$arg" in --json) json=1 ;; *) args+=("$arg") ;; esac
done
verb=${args[0]:-status}
if [ -f "$state/refuse.$verb" ]; then
	echo "refused: $verb"
	exit 1
fi
envelope() {
	printf '{"version": 1, "command": "%s", "exit_code": %s, "error": null, "result": %s}\n' "$verb" "$1" "$2"
}
case "$verb" in
status)
	[ "$json" = 1 ] && envelope 0 "$(cat "$state/status.json" 2>/dev/null || echo '{"attention": [], "branches": []}')"
	exit 0
	;;
queue)
	[ "$json" = 1 ] && envelope 0 "$(cat "$state/queue.json" 2>/dev/null || echo '{"runs": []}')"
	exit 0
	;;
cancel)
	# Ends a stopped run, as dockhand cancel does.
	if [ -f "$state/queue.json" ]; then
		jq --arg name "${args[1]:-}" '.runs |= map(select(.name != $name))' "$state/queue.json" >"$state/queue.json.new" && mv "$state/queue.json.new" "$state/queue.json"
	fi
	echo "Stopped ${args[1]:-}; what it finished is kept."
	exit 0
	;;
path)
	echo "$state"
	exit 0
	;;
clean)
	# Marks every branch cleaned, as cleaning merged ones does: status
	# --all still lists them.
	jq '.branches |= map(.cleaned = true)' "$state/status.json" >"$state/status.json.new" 2>/dev/null && mv "$state/status.json.new" "$state/status.json"
	echo "Cleaned."
	exit 0
	;;
hint)
	echo "Next: dockhand diff -b x, then dockhand tidy -b x"
	exit 0
	;;
leak)
	echo "token gho_0123456789abcdefghijklmnopqrstuvwxyz"
	exit 0
	;;
esac
if [ "$json" = 1 ]; then
	envelope "$(cat "$state/json_exit" 2>/dev/null || echo 0)" '{}'
	exit "$(cat "$state/proc_exit" 2>/dev/null || echo 0)"
fi
echo "did $verb"
