#!/bin/sh
set -eu

scan() {
    case "${1:-}" in
        audio) curl \
                --data-binary \
                '{ "jsonrpc": "2.0", "method": "AudioLibrary.Scan", "id": "transmission"}' \
                -H 'content-type: application/json;' \
                http://172.18.0.1:8080/jsonrpc ;;
        video) curl \
                --data-binary \
                '{ "jsonrpc": "2.0", "method": "VideoLibrary.Scan", "id": "transmission"}' \
                -H 'content-type: application/json;' \
                http://172.18.0.1:8080/jsonrpc ;;
        *) scan video; scan audio ;;
    esac
}

starts_with() {
    [ "${1##$2}" != "$1" ]
}

is_in_dir() {
    ! starts_with "$(realpath --relative-base "$1" "$2")" '/'
}

if [ -z "${TR_TORRENT_DIR:-}" ]
then
    scan
elif is_in_dir '/var/lib/transmission/Downloads/TV Shows' "$TR_TORRENT_DIR"
then
    scan video
elif is_in_dir '/var/lib/transmission/Downloads/Movies' "$TR_TORRENT_DIR"
then
    scan video
elif is_in_dir '/var/lib/transmission/Downloads/Music' "$TR_TORRENT_DIR"
then
    scan audio
else
    scan
fi
