#!/bin/sh

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

timestamp() {
  blacki '\T'
}

path() {
  yellowb '\w/'
}

repo_status() {
  inner="$(__git_ps1 "%s")"
  if [ -n "$inner" ]; then
    OUT="$(git status --short --branch --porcelain 2>/dev/null)"
    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="^^^ $inner vvv"
    elif [ -n "$IS_AHEAD" ]; then
      BRANCH_MARKER="^ $inner ^"
    elif [ -n "$IS_BEHIND" ]; then
      BRANCH_MARKER="v $inner v"
    else
      BRANCH_MARKER="$inner"
    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"

    printf ' - '
    blacki "$(git rev-parse HEAD)"
  fi
}

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
