#!/bin/sh
#
# Search books by title via Gutendex API.
#

[ -z "$1" ] && {
        printf "Usage: %s <book title>\n" "$0"
        exit 1
}

fetch_book_by_title() {
        title="$1"
        search_title=$(printf '%s' "$title" | jq -sRr @uri)

        curl -s "https://openlibrary.org/search.json?q=$search_title" |
        jq -r '
          .docs[0] as $d
          | ($d.author_name[0] // "Unknown")
            + ". "
            + ($d.title // "No title")
            + (if ($d.key // null) then
                 ". Work ID: " + ($d.key | split("/")[-1])
               else
                 ""
              end)
        '
}

fetch_book_by_title "$1"
