#!/bin/sh
# Catalogue requests write only into InkHub's private cache and Books.
set -eu
root=${INKHUB_REMARKABLE_ROOT:-/home/root/inkhub-dev}
fail() { printf '%s\n' "$*" >&2; exit 1; }
[ "$#" -ge 3 ] || fail 'A catalogue operation, address and destination are required.'
case "$1" in
    fetch) [ "$#" -eq 3 ] || fail 'A feed request needs one address and destination.'; base="$root/cache/opds" ;;
    download) [ "$#" -le 4 ] || fail 'A download needs one address, destination and optional size.'; base="$root/books" ;;
    *) fail 'That catalogue operation is not supported.' ;;
esac
# Resolve the parent after creating it, refusing traversal and symlink escapes.
case "$3" in "$base/"*) ;; *) fail 'That destination is outside InkHub storage.' ;; esac
case "/${3#"$base/"}/" in */../*|*/./*) fail 'That destination contains a relative path.' ;; esac
[ ! -L "$3" ] || fail 'That destination is a symbolic link.'
root_real=$(cd "$root" && pwd -P)
[ ! -L "$base" ] || fail 'InkHub storage is a symbolic link.'
mkdir -p "$base"
base_real=$(cd "$base" && pwd -P)
case "$base_real/" in "$root_real/"*) ;; *) fail 'InkHub storage leaves its private root.' ;; esac
parent=$(dirname "$3")
# Validate existing ancestors before creating anything under a symlink.
ancestor=$parent
while [ ! -d "$ancestor" ]; do ancestor=$(dirname "$ancestor"); done
ancestor_real=$(cd "$ancestor" && pwd -P)
case "$ancestor_real/" in "$base_real/"*) ;; *) fail 'That destination leaves InkHub storage.' ;; esac
mkdir -p "$parent"
parent_real=$(cd "$parent" && pwd -P)
case "$parent_real/" in "$base_real/"*) ;; *) fail 'That destination leaves InkHub storage.' ;; esac
export LIBRA2_OPDS_LAYOUT="$root/opds.conf"
export LIBRA2_OPDS_CURL="$root/bin/curl"
export LIBRA2_OPDS_NAME_FILE="$root/os-name"
export LIBRA2_OPDS_RESOLVE="$root/bin/remarkable-resolve"
export LIBRA2_OPDS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
exec "$root/bin/libra2-opds" "$@"
