#!/bin/sh

alias to_utf8='iconv -f latin1 -t utf8'
alias curl_GET='curl -X GET -s -G'

BASE_URL=https://www.keinverlag.de

kv_author_id () {
  if [ $# -ne 1 ]; then
    echo Please call kv_author_id with an author name. >/dev/stderr
    exit 1
  fi

  author_name=$1

  curl_GET "$BASE_URL/$author_name.kv" \
    | to_utf8 \
    | sed -n 's/.*autor=\([0-9]\+\).*/\1/p' \
    | head -1
}

kv_text () {
  if [ $# -ne 1 ]; then
    echo Please call kv_text with a text ID. >/dev/stderr
    exit 1
  fi

  text_id=$1

  curl_GET "$BASE_URL/$text_id.text" \
    | to_utf8 \
    | sed -n '/<h1>/,/<!-- Kommentarbox -->/p' \
    | sed 's/<h3>.\+<\/h3>//g' \
    | pandoc -f html -t plain
}

kv_author_texts () {
  if [ $# -ne 1 ]; then
    echo Please call kv_author_texts with an author ID. >/dev/stderr
    exit 1
  fi

  author_id=$1

  curl_GET "$BASE_URL/autorentexte.php" -d sortby=tnr -d start=0 -d limit=10000 -d autor="$author_id" \
    | to_utf8 \
    | sed -n 's/.*<li><a href="\([0-9]\+\)\.text">.*/\1/p'
}

case $1 in
  text)
    shift
    kv_text "$@";;
  author)
    shift
    for text_id in $(kv_author_texts "$(kv_author_id "$@")" | uniq); do
      kv_text "$text_id"
    done ;;
  *)
    echo >/dev/stderr "Usage: $0 text|author ID"
esac
