# powerline prompt
# requires: aifont (MesloLGS NF + ai/syui icons)

_has_aifont() {
  [[ -f "$HOME/Library/Fonts/aifont.ttf" ]] || [[ -f "$HOME/.local/share/fonts/aifont.ttf" ]]
}

_powerline_git() {
  local branch=$(git symbolic-ref --short HEAD 2>/dev/null) || return
  local dirty=""
  [[ -n $(git status --porcelain 2>/dev/null) ]] && dirty="*"
  echo "${branch}${dirty}"
}

_powerline_icon() {
  case "$USER" in
    syui) echo $'\ue002' ;;
    ai)   echo $'\ue001' ;;
    *)    echo "❯" ;;
  esac
}

_powerline_prompt() {
  local icon=$(_powerline_icon)
  local sep=$'\ue0b0'
  local dir="${PWD/#$HOME/~}"
  local git=$(_powerline_git)

  local prompt=""
  local icon_color="yellow"
  [[ -n "$SSH_CONNECTION" ]] && icon_color="cyan"
  if [[ -n "$icon" ]]; then
    prompt+="%F{${icon_color}}%K{black} ${icon} %k%f"
    prompt+="%F{black}%K{234}${sep}%f"
  else
    prompt+="%F{234}${sep}%f"
  fi
  prompt+="%F{yellow}%K{234} $USER %k%f"
  prompt+="%F{234}%K{236}${sep}%f"
  prompt+="%F{white}%K{236} ${dir} %k%f"

  if [[ -n "$git" ]]; then
    prompt+="%F{236}%K{234}${sep}%f"
    prompt+="%F{cyan}%K{234}  ${git} %k%f"
    prompt+="%F{234}${sep}%f"
  else
    prompt+="%F{236}${sep}%f"
  fi
  prompt+="%k%f "

  echo "$prompt"
}

if _has_aifont; then
  setopt PROMPT_SUBST
  PROMPT='$(_powerline_prompt)'
fi
