#!/usr/bin/env bash

RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
GRAY=$(tput setaf 8)
ITALIC=$(tput sitm)
RESET=$(tput sgr0)

format_command_time() {
  local x="$1"
  local ms="$((x % 1000))"
  x="$((x / 1000))"
  local sec="$((x % 60))"
  x="$((x / 60))"
  local min="$((x % 60))"
  x="$((x / 60))"
  local hour="$((x % 24))"
  local day="$((x / 24))"
  local timestr
  if [ "$day" -gt 0 ]; then
    timestr="${day}d "
  fi
  if [ "$hour" -gt 0 ]; then
    timestr="$timestr${hour}h "
  fi
  if [ "$min" -gt 0 ]; then
    timestr="$timestr${min}m "
  fi
  if [ "$sec" -gt 0 ]; then
    timestr="$timestr${sec}s "
  fi
  timestr="$timestr${ms}ms"
  printf '%s' "$timestr"
}

last_command_timer() {
  last_command_start=${last_command_start:-$(date +%s%3N)}
}

set_prompt() {
  if [ $? -eq 0 ]; then
    prompt_color="$GREEN"
  else
    prompt_color="$RED"
  fi
  if [ -n "$last_command_start" ]; then
    last_command_length=$(format_command_time "$(($(date +%s%3N) - last_command_start))")
    unset last_command_start
    last_command_stats="$ITALIC${MAGENTA}Completed in $last_command_length.$RESET\n"
  else
    last_command_stats=
  fi
  git_branch=$(git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
  if [ -n "$git_branch" ]; then
    local git_status
    git_status=$(git status --porcelain)
    if [ -n "$git_status" ]; then
      git_symbol=" $RED "
    else
      git_symbol=" $GREEN "
    fi
  else
    git_symbol=
  fi
  PS1="\n$last_command_stats\[$GRAY\]$(whoami)@$(hostname)\[$RESET\]\n\[$BLUE\]\w\[$RESET\]$git_symbol\[$YELLOW\]$git_branch\[$RESET\]\n\[$prompt_color\]❯\[$RESET\] "
}

trap 'last_command_timer' DEBUG
PROMPT_COMMAND=set_prompt
