#!/usr/bin/env bash
set -euo pipefail

QUOTES_FILE="${QUOTES_FILE:-$HOME/.local/share/os/quotes.txt}"

usage() {
  cat <<'EOF'
Usage: quotes.sh <command> [args]

Commands:
  add <quote> <author>   Add a quote as: quote {{ author }}
  today                  Print today's deterministic quote
EOF
}

trim() {
  local value="$1"
  value="${value#"${value%%[![:space:]]*}"}"
  value="${value%"${value##*[![:space:]]}"}"
  printf '%s' "$value"
}

ensure_file() {
  mkdir -p "$(dirname "$QUOTES_FILE")"

  if [ ! -e "$QUOTES_FILE" ]; then
    touch "$QUOTES_FILE"
  fi
}

add_quote() {
  if [ "$#" -ne 2 ]; then
    echo 'Usage: quotes.sh add <quote> <author>' >&2
    exit 1
  fi

  ensure_file

  local quote author
  quote="$(trim "$1")"
  author="$(trim "$2")"

  if [ -z "$quote" ] || [ -z "$author" ]; then
    echo 'Quote and author must be non-empty' >&2
    exit 1
  fi

  if [[ "$quote" == *$'\n'* ]] || [[ "$author" == *$'\n'* ]]; then
    echo 'Quote and author must be single-line values' >&2
    exit 1
  fi

  if [ -s "$QUOTES_FILE" ] && [ "$(tail -c 1 "$QUOTES_FILE" 2>/dev/null || true)" != $'\n' ]; then
    printf '\n' >> "$QUOTES_FILE"
  fi

  printf '%s {{ %s }}\n' "$quote" "$author" >> "$QUOTES_FILE"
}

today_quote() {
  ensure_file

  local day hash
  day="$(date +%F)"
  hash="$(printf '%s' "$day" | cksum | awk '{print $1}')"

  awk -v hash="$hash" '
    NF { lines[count++] = $0 }
    END {
      if (count == 0) {
        exit 1
      }

      line = lines[hash % count]
      if (match(line, / \{\{ .* \}\}$/)) {
        quote = substr(line, 1, RSTART - 1)
        author = substr(line, RSTART)
        sub(/^ \{\{ /, "", author)
        sub(/ \}\}$/, "", author)
        printf "%s\n-- %s\n", quote, author
      } else {
        print line
      }
    }
  ' "$QUOTES_FILE" || {
    echo "No quotes found in $QUOTES_FILE" >&2
    exit 1
  }
}

case "${1:-}" in
  add)
    shift
    add_quote "$@"
    ;;
  today|daily)
    today_quote
    ;;
  -h|--help|help)
    usage
    ;;
  *)
    usage >&2
    exit 1
    ;;
esac
