#!/bin/sh

repo_status_git() {
	BRANCH_NAME="$(git rev-parse --abbrev-ref HEAD)"
	OUT="$(git status --short --branch --porcelain)"
	BRANCH_LINE="$(echo "$OUT" | head -n 1)"
	DIFF_LINES="$(echo "$OUT" | tail -n +2)"

	if echo "$BRANCH_LINE" | grep -q 'ahead'; then
		IS_AHEAD=1
	fi
	if echo "$BRANCH_LINE" | grep -q 'behind'; then
		IS_BEHIND=1
	fi

	if [ -n "$IS_AHEAD" ] && [ -n "$IS_BEHIND" ]; then
		BRANCH_MARKER="^^^ $BRANCH_NAME vvv"
	elif [ -n "$IS_AHEAD" ]; then
		BRANCH_MARKER="^ $BRANCH_NAME ^"
	elif [ -n "$IS_BEHIND" ]; then
		BRANCH_MARKER="v $BRANCH_NAME v"
	else
		BRANCH_MARKER="$BRANCH_NAME"
	fi

	if echo "$DIFF_LINES" | grep -q '^[A|D|M| ][M|D| ]'; then
		HAS_DIFF=1
	fi

	if echo "$DIFF_LINES" | grep -q '^[?][?]'; then
		HAS_UNTRACKED=1
	fi

	if [ -n "$HAS_DIFF" ]; then
		COLOR_FN=redb
		LINE="{$BRANCH_MARKER}"
	elif [ -n "$IS_AHEAD" ] || [ -n "$IS_BEHIND" ]; then
		COLOR_FN=bluei
		LINE="[$BRANCH_MARKER]"
	elif [ -n "$HAS_UNTRACKED" ]; then
		COLOR_FN=lightblue
		LINE="($BRANCH_MARKER)"
	else
		COLOR_FN=green
		LINE="($BRANCH_MARKER)"
	fi

	"$COLOR_FN" "$LINE"

	blacki " - git/$(git rev-parse HEAD)"
}

repo_status_fossil() {
	BRANCH_NAME="$(fossil branch current)"

	if [ -n "$(fossil extras)" ]; then
		HAS_UNTRACKED=1
	fi

	BRANCH_MARKER="$BRANCH_NAME"

	if [ -n "${HAS_UNTRACKED:-}" ]; then
		COLOR_FN=lightblue
		LINE="($BRANCH_MARKER)"
	else
		COLOR_FN=green
		LINE="($BRANCH_MARKER)"
	fi

	"$COLOR_FN" "$LINE"

	# echo 'FOSSIL!'
	# printf '%s' "$BRANCH_NAME"
	blacki " - fossil/$(fossil info | awk '/^checkout:/ { print $2 }')"
}

repo_status_mercurial() {
	BRANCH_NAME="$(hg branch)"
}

repo_status() {
	dir="$(basename "$PWD")"
	if   [ -d .git ]; then
		repo_status_git
	elif [ -f "$dir.fossil" ]; then
		repo_status_fossil
	elif [ -d .hg ]; then
		repo_status_mercurial
	fi
}


error_marker() {
  STATUS=$?
  if [ "$STATUS" != 0 ]; then
    redb " (!! $STATUS !!) "
  fi
}

timestamp() {
  blacki '\T'
}

path() {
  yellowb '\w/'
}

guix_env() {
  if [ "$GUIX_ENVIRONMENT" != '' ]; then
    printf '\n'
    blacki '~> '
    purple 'guix environment '
    printf '('
    blueb "$GUIX_ENVIRONMENT"
    printf ')'
  fi
}

in_nix_shell() {
  if [ "$IN_NIX_SHELL" != '' ]; then
    printf '\n'
    blacki '~> '
    purpleb "$IN_NIX_SHELL "
    purple 'nix-shell '
    printf '('
    # $name comes from the mkShell declaration
    # shellcheck disable=2154
    blueb "$name"
    printf ')'
  fi
}

PS1='`error_marker`'$(timestamp)' '$(path)' `repo_status``guix_env``in_nix_shell`
$ '
export PS1
