#!/usr/bin/env bash
set -xfeuo pipefail

state="${XDG_RUNTIME_DIR}/starship-sl-status"
checkout="${state}.checkout"
status="${state}.data"

if [[ "$PWD" != $(readlink -f "$state")* ]]; then
	rm -f "$state"
	root="$(sl root 2>/dev/null || true)"
	ln -s "$root" "$state"
	if [[ -z "${root}" ]]; then
		echo >"${status}"
		echo >"${checkout}"
		exit 0
	fi
fi

saved_cid=$(cat "${checkout}" 2>/dev/null || true)
root_cid=$(cat "${state}/.sl/checkoutidentifier" || true)
if [[ ${root_cid} != "${saved_cid}" ]]; then
	echo "${root_cid}" >"${checkout}"
	sl log -r . -T '{if(github_pull_request_number, "#{github_pull_request_number} @ ", if(bookmarks, "{bookmarks} @ "))}{node|short}{if(remotenames, ":{remotenames}")}' >"${status}"
fi

cat "$status" || true