#!/bin/bash

# blob:summary=Regenerate docs/commands.md from each command's own metadata
# blob:hidden=true

set -e

bin_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_dir="$(dirname "$bin_dir")"
output="$repo_dir/docs/commands.md"

metadata() {
  sed -n "s/^# blob:$2=//p" "$1" | head -1
}

area_of() {
  local name="${1#blob-}"
  printf '%s\n' "${name%%-*}"
}

{
  echo "# Commands"
  echo
  echo "Generated by \`blob-docs-commands\` from the \`# blob:summary=\` line in each"
  echo "file. Do not edit by hand."
  echo
  echo "Commands marked hidden are plumbing other commands call, and are left out"
  echo "of the \`blob\` listing."
  echo

  current_area=""
  for file in "$bin_dir"/blob-*; do
    [[ -f $file ]] || continue
    name="$(basename "$file")"
    area="$(area_of "$name")"

    if [[ $area != "$current_area" ]]; then
      echo
      echo "## $area"
      echo
      echo "| Command | Does | Arguments |"
      echo "| --- | --- | --- |"
      current_area="$area"
    fi

    summary="$(metadata "$file" summary)"
    args="$(metadata "$file" args)"
    [[ -n $summary ]] || summary="-"
    [[ -n $args ]] || args="-"
    if grep -q '^# blob:hidden=true' "$file"; then
      summary="$summary (hidden)"
    fi
    printf '| `%s` | %s | %s |\n' "$name" "$summary" "${args//|/\\|}"
  done

  echo
  echo "## Totals"
  echo
  printf '%s commands.\n' "$(ls "$bin_dir"/blob-* | wc -l)"
} > "$output"

echo "Wrote $output"
