#!/bin/zsh

### List cloned bundles.
#
# usage: antidote list [-h|--help] [-s|--short] [-d|--dirs] [-u|--url] [-j|--jsonl]
#
#function antidote-list {
  emulate -L zsh; setopt local_options $_adote_funcopts

  local -a o_help o_jsonl o_fields
  local arg ch
  for arg in "$@"; do
    case $arg in
      --) shift; break ;;
      -h|--help)  o_help+=($arg)  ;;
      -j|--jsonl) o_jsonl+=($arg) ;;
      -d|--dirs)  o_fields+=(d)   ;;
      -u|--url)   o_fields+=(u)   ;;
      -s|--short) o_fields+=(s)   ;;
      -[dus]*)
        for ch in ${(s::)arg[2,-1]}; do
          case $ch in
           d|u|s) o_fields+=($ch) ;;
           *) print -ru2 "antidote: error: unexpected $arg, try --help"; return 1 ;;
          esac
        done
        ;;
      -*) print -ru2 "antidote: error: unexpected $arg, try --help"; return 1 ;;
      *) print -ru2 "antidote: error: unexpected $arg, try --help"; return 1 ;;
    esac
    shift
  done

  if (( $#o_help )); then
    antidote-help list
    return
  fi

  if (( $# )); then
    print -ru2 "antidote: error: unexpected $1, try --help"
    return 1
  fi

  local bundledir url short
  local -a output=() parts=()
  local -a bundles=($(antidote-home)/**/.git(/N))

  for bundledir in $bundles; do
    parts=()
    bundledir=${bundledir:h}
    url=$(git -C "$bundledir" config remote.origin.url)
    short=${url%.git}
    short=${short#https://github.com/}

    if (( $#o_jsonl )); then
      printf '{"url":"%s","short_name":"%s","type":"repo","path":"%s"}\n' \
        "$url" "$short" "$bundledir"
      continue
    elif (( $#o_fields )); then
      for arg in $o_fields; do
        case $arg in
          d) parts+=($bundledir) ;;
          s) parts+=($short)     ;;
          u) parts+=($url)       ;;
        esac
      done
      output+=("$(printf '%s\n' ${(pj:\t:)parts})")
    else
      output+=("$(printf '%-64s %s\n' $url $bundledir)")
    fi
  done
  (( $#output )) && printf '%s\n' ${(o)output}

#}
