#!/usr/bin/env bash

print_in_color() {
  local color="$1"
  shift
  if [[ -z ${NO_COLOR+x} ]]; then
    printf "$color%b\e[0m\n" "$*"
  else
    printf "%b\n" "$*"
  fi
}
red() { print_in_color "\e[31m" "$*"; }
green() { print_in_color "\e[32m" "$*"; }

projectsrc="$HOME/.config/projectsrc"

_print_project_status () {
  project="$1"
  cd "$HOME/$project" || return

  branch=$(git branch --show-current)
  if [ -z "$branch" ]; then
    return
  fi

  remote="origin"
  remotes=$(git remote)
  if ! echo "$remotes" | grep -q "^$remote$"; then
    remote=$(echo "$remotes" | head -n 1)
  fi


  ahead=$(git rev-list --count "$remote/$branch"..HEAD)
  if [ "$ahead" -eq 0 ]; then
    ahead=$(green "$ahead")
  else
    ahead=$(red "$ahead")
    project=$(red "$project")
  fi

  dirty=$(git status --porcelain | wc -l)
  if [ "$dirty" -eq 0 ]; then
    dirty=$(green "$dirty")
  else
    dirty=$(red "$dirty")
    project=$(red "$project")
  fi

  printf "%s\t%s\t%s\t%s\n" \
    "$project" \
    "$branch" \
    "$ahead" \
    "$dirty"
}

_print_projects_status () {
  while read -r next_project
  do
    if [ -z "$next_project" ]; then
      continue
    fi

    if [ ! -d "$HOME/$next_project" ]; then
      continue
    fi

    _print_project_status "$next_project"
  done < "$projectsrc"
}

_print_projects_status | column -t -s$'\t' --table-columns 'Project,Branch,Ahead,Dirty Files'