#!/usr/bin/env sh
#
# search Grady Ward's Moby Project thesaurus with a fuzzy-finder
# https://en.wikipedia.org/wiki/Moby_Project
#
# Usage:
#
#   thes
#   thes balloon

while getopts ':h' opt; do
  case "${opt}" in
    h)
      awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
      exit 0
      ;;
    \?)
      printf "%s: Unrecognized option: '-%c'\n" "${0##*/}" "${OPTARG}" >&2
      exit 1
      ;;
  esac
done
shift "$((OPTIND - 1))"

THES_URL='https://www.gutenberg.org/files/3202/files/mthesaur.txt'
THES_CACHE="${HOME}/.cache/mthesaur.txt"

if [ ! -e "${THES_CACHE}" ]; then
  mkdir -p -- "${HOME}/.cache"
  curl --silent --show-error "${THES_URL}" -o "${THES_CACHE}"
  # curl -sS -C - "${THES_URL}" -o "${THES_CACHE}"
fi

if [ -e "${THES_CACHE}" ]; then
  # shellcheck disable=SC2016
  awk 'BEGIN { FS=","; OFS="\t" } { print NR, $1 }' "${THES_CACHE}" \
    | fzy ${@:+-q "$@"} \
    | cut -f1 \
    | xe -p % awk -F, -v 'lnum=%' '
        NR == lnum { for (i=1; i<= NF; i+=1) print $i; exit }
    ' "${THES_CACHE}" \
    | git column --mode=column
fi
