#! /bin/zsh

zmodload zsh/datetime

OVER_PROMPT_CFG="/etc/over/env/prompt.cfg"
OVER_PROMPT_TITLE=""

which ddcutil > /dev/null
if [[ $? -eq 0 ]]; then
	local I2C_IDS=($(ddcutil detect --terse | grep "I2C bus" | sed "s/^.*-//"))
	export OVER_ENV_MONITORS_I2C=${(j|:|)I2C_IDS}
fi

if [[ -a "$OVER_PROMPT_CFG" ]]; then
	source "$OVER_PROMPT_CFG"
fi

if [[ "${TERM}" == "screen" || "${TERM:0:4}" == "tmux" ]]; then
	function __over_prompt_set_title {
		if [[ -n "${OVER_PROMPT_TITLE}" ]]; then
			print -Pn "\033k${OVER_PROMPT_TITLE}\033\134"
		else
			print -Pn "\033k${@}\033\134"
		fi
	}
else
	function __over_prompt_set_title { }
fi

function set_title {
	OVER_PROMPT_TITLE="$1"
}

function __over_prompt_preexec {
	__over_prompt_set_title "${1}"
	OVER_PROMPT_CMD_START=${EPOCHSECONDS}
}

function __over_prompt_sysload {
	LOADAVG=($(< /proc/loadavg))
	echo $(($LOADAVG[1] / $(nproc)))
}

function __over_prompt_precmd {
	__over_prompt_set_title "${PWD//*\//} (${PWD})"
	LOAD_NORM=$(__over_prompt_sysload)
	if [[ $LOAD_NORM -lt 3 ]]; then
		python3 /usr/share/over-env/prompt.py "${COLUMNS}" "${PWD}" "${OVER_PROMPT_LAST_REFRESH}" "${OVER_PROMPT_SYSLOAD_WARN:=1.25}" "${OVER_PROMPT_SYSLOAD_YELL:=3.0}" "${OVER_PROMPT_FREESPACE_WARN:=0.15}" "${OVER_PROMPT_FREESPACE_YELL:=0.05}" "${OVER_PROMPT_CMD_START}"
	else
		echo "Overloaded"
	fi
	PS1="$(print "%(?.%{\e[1;36m%}.%{\e[1;31m%}%?%{\e[0m%}:%{\e[1;31m%})%(\!.#.$)%{\e[0m%} ")"
	OVER_PROMPT_LAST_REFRESH=${EPOCHSECONDS}
	OVER_PROMPT_CMD_START=0
	
	if [[ "${OVER_PROMPT_BELL:=1}" == "1" ]]; then
		print -Pn "\007"
	fi
}

unset OVER_PROMPT_CFG
unset RPS1
