#!/bin/sh
set -eu

usage() {
  printf '%s\n' 'Usage: tapeline status | search [--q TEXT] [--provider ID] [--feed ID] [--kind KIND] [--since TIME] [--until TIME] [--security CODE] [--limit N] [--exclude-digest]' >&2
  exit 2
}

[ "$#" -gt 0 ] || usage
command=$1
shift
case $command in
  search|status) ;;
  *) usage ;;
esac
[ -n "${TAPELINE_URL:-}" ] || { printf '%s\n' 'Set TAPELINE_URL to your Tapeline origin.' >&2; exit 2; }
case $TAPELINE_URL in
  http://*|https://*) ;;
  *) printf '%s\n' 'TAPELINE_URL must use http or https.' >&2; exit 2 ;;
esac

# Recursive parsing accumulates curl arguments as distinct shell words, without eval.
request() {
  remaining=$1
  shift
  if [ "$remaining" -eq 0 ]; then
    exec curl --fail-with-body --silent --show-error --get --connect-timeout 10 --max-time 30 \
      --user-agent 'tapeline/1' --header 'Accept: application/json' "$@" "${TAPELINE_URL%/}/api/$command"
  fi
  option=$1
  shift
  remaining=$((remaining - 1))
  [ "$command" = search ] || usage
  case $option in
    --exclude-digest)
      request "$remaining" "$@" --data-urlencode 'exclude_digest=true'
      ;;
    --q|--provider|--feed|--kind|--since|--until|--security|--limit|--exclude_digest)
      [ "$remaining" -gt 0 ] || usage
      value=$1
      shift
      remaining=$((remaining - 1))
      request "$remaining" "$@" --data-urlencode "${option#--}=$value"
      ;;
    *) usage ;;
  esac
}
request "$#" "$@"
