#compdef jj

function __list_commands {
  local -a subcmds
  local line dir next help helpfile command
  dir="$1"
  # the parens after the glob contains "glob qualifiers" (see man zshexpn):
  # * executable
  # - follow symlinks
  # , "or" separator
  # / directories
  for file in "$dir"/*(-*,/); do
    command=$(basename "$file")

    if [[ -d "$file" ]]; then
      helpfile="$file/help"
      if [[ -f "$helpfile" ]]; then
        help=$(head -n 1 "$helpfile")
      else
        help="$command commands"
      fi
    else
      helpfile="$file.help"
      if [[ -f "$helpfile" ]]; then
        help=$(head -n 1 "$helpfile")
      else
        help=$(sed -nE -e '/^#!/d' -e '/^#/{s/^# *//; p; q;}' "$file")
      fi
    fi

    subcmds=($subcmds "$command:\"$help\"")
  done

  _arguments -C ": :(($subcmds))" "*::arg:->args"

  next="$dir/$line[1]"
  if [[ ! -z $line[1] && -d "$next" ]]; then
    __list_commands "$next"
  elif [[ ! -z $line[1] && -x "$next" ]]; then
    # You could imagine wanting to customize the '*:file:_files' fallback
    # at some point, but I'm not going to worry about that for now.
    _arguments -A '-*' \
      '--help[print help text]' \
      '--cat[print script contents]' \
      '--which[print script path]' \
      '--edit[open script for editing]' \
      '--really[suppress special argument handling]' \
      '*:file:_files'
  elif [[ ! -z $line[1] && ! -f "$next" ]]; then
    _arguments "--new[create a new script]"
  fi
}

__list_commands ${SD_ROOT:-"$HOME/bin"}
