#!/usr/bin/env bash
set -u

workspace_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
manifest="$workspace_root/workspace.yml"

if [[ ! -f "$manifest" ]]; then
  printf 'workspace manifest not found: %s\n' "$manifest" >&2
  exit 1
fi

printf '%-30s %-18s %-7s %s\n' REPOSITORY BRANCH STATE UPSTREAM

while IFS= read -r relative_path; do
  if [[ "$relative_path" == "." ]]; then
    repository_name=workspace
    repository_path=$workspace_root
  else
    repository_name=$(basename "$relative_path")
    repository_path="$workspace_root/$relative_path"
  fi

  if [[ ! -d "$repository_path/.git" ]]; then
    printf '%-30s %-18s %-7s %s\n' "$repository_name" - missing "$relative_path"
    continue
  fi

  branch=$(git -C "$repository_path" branch --show-current)
  if [[ -z "$branch" ]]; then
    branch="detached@$(git -C "$repository_path" rev-parse --short HEAD)"
  fi

  if [[ -n $(git -C "$repository_path" status --porcelain) ]]; then
    state=dirty
  else
    state=clean
  fi

  upstream=$(git -C "$repository_path" rev-parse \
    --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)
  if [[ -n "$upstream" ]]; then
    read -r behind ahead < <(git -C "$repository_path" rev-list \
      --left-right --count "$upstream...HEAD")
    tracking="ahead=$ahead behind=$behind ($upstream)"
  else
    tracking=untracked
  fi

  printf '%-30s %-18s %-7s %s\n' \
    "$repository_name" "$branch" "$state" "$tracking"
done < <(
  printf '.\n'
  awk '$1 == "path:" { print $2 }' "$manifest"
)
