#!/usr/bin/env bash

error-marker() {
  if [ $? != 0 ]; then
    redb ' (!!) ' | tr -d '\n'
  fi
}

timestamp() {
  blacki '\T' | tr -d '\n'
}

path() {
  yellowb '\w/' | tr -d '\n'
}

repo-status() {
  branch="$(git branch --show-current 2> /dev/null)"
  if [ "$branch" != '' ]; then
    OUT="$(env LANG=en_US.UTF-8 git status)"
    if ! git diff --quiet &> /dev/null || ! git diff --staged --quiet &> /dev/null; then
      redb "{$branch}" | tr -d '\n'
    elif grep 'to publish your local commits' <(echo "$OUT") > /dev/null; then
      bluei "[^${branch}^]" | tr -d '\n'
    elif grep 'to update your local branch' <(echo "$OUT") > /dev/null; then
      bluei "[v${branch}v]" | tr -d '\n'
    else
      green "(${branch})" | tr -d '\n'
    fi
    printf ' - '
    blacki "$(git rev-parse HEAD | head -c 7)" | tr -d '\n'
  fi
}

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

in-nix-shell() {
  if [ "$IN_NIX_SHELL" != '' ]; then
    printf '\n'
    blacki '~> ' | tr -d '\n'
    purpleb "$IN_NIX_SHELL " | tr -d '\n'
    purple 'nix-shell ' | tr -d '\n'
    printf '('
    blueb "$name" | tr -d '\n'
    printf ')'
  fi
}

export PS1='`error-marker`'$(timestamp)' '$(path)' `repo-status``guix-env``in-nix-shell`
$ '
