#!/usr/bin/env sh
#
# colour definitions for parts of $PS1.

# do we even have a terminal we can do things to?
we_have_term() {
  [ -n "${TERM}" ] && [ "${TERM}" != dumb ]
}

raw_termattr() {
  if [ -n "${TERM}" ] && [ "${TERM}" != dumb ]; then
    # shellcheck disable=SC2249
    for attr in "$@"; do
      case "${attr}" in
      normal)
        tput sgr0
        ;;
      red)
        tput setaf 1
        ;;
      blue)
        tput setaf 4
        ;;
      bold)
        tput bold
        ;;
      esac
    done
  fi
}

# Output terminal attribute changing sequence, if there's a terminal.
# Also output output bash $PS1 sequences to tell bash it's
# non-printing characters.
termattr() {
  printf '\['
  raw_termattr "$@"
  printf '\]'
}

########################################################################
# Collect info to show in $PS1

# shellcheck disable=SC2312
find_git_root() {
  (
    set -e
    while [ "$(pwd)" != / ]; do
      if [ -d .git ]; then
        pwd
        break
      else
        cd ..
      fi
    done
  )
}

is_git_repo() {
  # shellcheck disable=SC2311
  case "$(find_git_root)" in
  /*) return 0 ;;
  *) return 1 ;;
  esac
}

get_git_branch() {
  # shellcheck disable=SC2312
  git branch --no-color | awk 'BEGIN {max = 30 } /^\* / { name = $2; if (length(name) > max) name = "..." substr(name, length(name) - max); print name }'
}

########################################################################
# Set window title for terminal emulator, screen.

set_window_title() {
  # shellcheck disable=SC2249
  case "${TERM}" in
  xterm*)
    printf '\033]1;%s\07' "$1" >/dev/tty
    printf '\033]2;%s\07' "$1" >/dev/tty
    ;;
  screen)
    # shellcheck disable=SC1003
    printf '\ek%s\e\\' "$1" >/dev/tty
    ;;
  esac
}

########################################################################
# Dynamically change $PS1 or output other things just before the prompt.

wrap_if_nonempty() {
  thing="$1"
  before="$2"
  after="$3"

  if [ -n "${thing}" ]; then
    printf '%s%s%s' "${before}" "${thing}" "${after}"
  fi
}

define_ps1() {
  termattr bold blue
  # shellcheck disable=SC2312
  date '+%H:%M' | tr -d '\n'
  hostname="$(hostname)"
  case "${hostname}" in
  exolobe3)
    printf ' \w '
    ;;
  *)
    termattr red
    printf ' %s' "${hostname}"
    termattr bold blue
    printf ':\w '
    ;;
  esac
  termattr normal

  # shellcheck disable=SC2310
  if is_git_repo; then
    # shellcheck disable=SC2311,SC2312
    wrap_if_nonempty "$(get_git_branch)" "$(termattr bold blue)[" "]$(termattr normal)"
  fi

  termattr bold blue
  printf '\$ '
  termattr normal
}

define_window_title() {
  # shellcheck disable=SC2312
  printf "%s:" "$(hostname)"
  # shellcheck disable=SC2312
  pwd | sed "s,${HOME},~,"
}

tell_about_exit_code() {
  exit_code="$1"
  if [ "${exit_code}" != 0 ]; then
    raw_termattr bold red
    printf '[PREVIOUS COMMAND EXIT: %s]\n' "${exit_code}"
    raw_termattr normal
  fi
}

prompt_set_window_title() {
  # shellcheck disable=SC2311,SC2312
  set_window_title "$(define_window_title)"
}
prompt_command() {
  tell_about_exit_code "$?"
  # shellcheck disable=SC2311,SC2312
  PS1="$(define_ps1)"
  prompt_set_window_title
}

###############

# ulimit -c 0
umask 002

# get environment variables from systemd, if any are set.
# if systemctl --user show-environment >/dev/null 2>&1; then
#   # shellcheck disable=SC2312,SC3001,SC1090
#   . <(systemctl --user show-environment | sed 's/^/export /')
# fi

if command -v emacs >/dev/null; then
  export EDITOR=emacs
else
  export EDITOR=vi
fi
# shellcheck disable=SC2250
export PATH="$HOME/.cargo/bin:$PATH:$HOME/bin:$HOME/.local/bin:$HOME/.radicle/bin:/usr/games"
export PAGER=less
export LESSCHARSET=utf-8
export HISTCONTROL=ignoredups
export HISTFILESIZE=500
export DEBEMAIL=liw@liw.fi
export VIRSH_DEFAULT_CONNECT_URI=qemu:///system
export LANG=en_US.UTF-8
export LC_COLLATE=fi_FI.UTF-8
export LC_TIME=en_GB
export ANSIBLE_ROLES_PATH="${HOME}/pers/puomi/git/roles:${HOME}/pers/debian-ansible/roles"
export STARSHIP_CONFIG=~/.config/starship/config.toml
unset HISTFILE

if [ -e /scratch/cargo-cache ]; then
  export CARGO_TARGET_DIR="/scratch/cargo-cache"
elif [ -e "${HOME}/tmp/cargo" ]; then
  export CARGO_TARGET_DIR="${HOME}/tmp/cargo"
elif [ -e "${HOME}/cargo" ]; then
  export CARGO_TARGET_DIR="${HOME}/cargo"
fi

PROMPT_DIRTRIM=1

# set +H
# set +o histexpand
if [ -n "${PS1}" ]; then
  bind -r ''
fi

gotcmd() {
  command -v "$1" >/dev/null
}

if command -v starship >/dev/null 2>&1; then
  export PROMPT_COMMAND=prompt_set_window_title
  # shellcheck disable=SC2312
  eval "$(starship init bash)"
else
  export PROMPT_COMMAND=prompt_command
fi

if [ -e "${HOME}/.cargo/env" ]; then
  . "${HOME}/.cargo/env"
fi

if command -v pathdedup >/dev/null; then
  PATH="$(pathdedup)"
fi

# if gotcmd zoxide; then
#   eval "$(zoxide init --hook prompt bash)"
# fi
