#!/usr/bin/zsh
set -e

cmd=$1
bookid=${2/.md}

function value () {
    echo $@
    exit 0
}

case $cmd in
    meta)
        value $bookid.yml
        ;;
    mds)
        alias git="${GIT:-/usr/bin/git}"
        alias sed="${SED:-/usr/bin/sed}"
        alias sort="${SORT:-/usr/bin/sort}"
        # wrangle our own sorting so NNN.md comes before NNN-foo/bar.md
        git ls-files "$PROJECT.md" "$PROJECT-*.md" "$bookid.md" "$bookid-**.md" |
            sed -E 's/\.md$/,md/' |
            LANG=c sort -n |
            sed -E 's/,md$/.md/'
        exit 0
        ;;
  srcid)
      alias yq="${YQ:-/usr/bin/yq}"
      $0 meta $2 | read meta
      if [[ -f $meta ]] && yq -e 'has("source")' $meta >/dev/null; then
          yq -r '[.source[] | select(.type == "bookid")][0].text' $meta | read bookid
          value $bookid
      fi
      ;;
esac

exit 1
