#!/bin/sh
# Return a book to the library (e.g. onleihe)
# https://readium.org/lcp-specs/releases/lsd/latest.html
set -e
if [ $# -lt 1 ]; then
    echo .lcpl file parameter missing
    exit 1
fi

lcplFile=$1
echo "hi $lcplFile"

statusUrl=$(jq -r '.links[] | select(.rel=="status") | .href' < "$lcplFile")
echo "License status URL: $statusUrl"

statusContent=$(curl -s "$statusUrl")

status=$(echo "$statusContent" | jq -r '.status')
echo "License status: $status"

if [ "$status" = "ready" ]; then
    echo "Need to register a device"
    registerUrlTpl=$(echo "$statusContent" | jq -r '.links[] | select(.rel=="register") | .href')
    echo "Registration URL template: $registerUrlTpl"

    registerUrl=$(echo "$registerUrlTpl" | sed 's/{&id,name}/\&id=0xdeadbeef\&name=Kindel/')
    echo "Registration URL:          $registerUrl"

    #register the device
    statusContent=$(curl -s -XPOST "$registerUrl")
    status=$(echo "$statusContent" | jq -r '.status')
    echo "License status: $status"
fi

if [ "$status" = "active" ]; then
    echo "Book can be returned"

    returnUrlTpl=$(echo "$statusContent" | jq -r '.links[] | select(.rel=="return") | .href')
    echo "Return URL template: $returnUrlTpl"

    returnUrl=$(echo "$returnUrlTpl" | sed 's#{?id,name}#\?id=0xdeadbeef\&name=Kindel#')
    echo "Return URL:          $returnUrl"

    #TEA's implementation has a bug: It returns the license, not the status
    licenseContent=$(curl -s -XPUT "$returnUrl")
    #echo $licenseContent

    statusContent=$(curl -s "$statusUrl")
    status=$(echo "$statusContent" | jq -r '.status')
    echo "License status: $status"
fi

if [ "$status" = "returned" ]; then
    echo "Book has been returned. All fine."
    exit 0
fi

echo "Unknown status $status. No idea what to do now."
exit 10
