#!/usr/bin/env nix-shell
#!nix-shell -i bash -p bash curl jq moreutils nix-prefetch
# shellcheck shell=bash
#
# inspired by <repo:nixos/nixpkgs:pkgs/development/libraries/duckdb/update.sh>

cd /home/colin/nixos
# cd "$(dirname "${BASH_SOURCE[0]}")"
# nixpkgs=$(while [[ ! -e .git ]]; do [[ ${PWD} != / ]] || exit 1; cd ..; done; echo "${PWD}")

repo=koreader
owner=koreader

msg() {
    echo "$*" >&2
}

get_latest() {
    curl ${GITHUB_TOKEN:+" -u \":$GITHUB_TOKEN\""} -s \
        "https://api.github.com/repos/${owner}/${repo}/releases/latest" | jq -r .tag_name
}

get_sha() {
    curl ${GITHUB_TOKEN:+" -u \":$GITHUB_TOKEN\""} -s \
        "https://api.github.com/repos/${owner}/${repo}/git/ref/tags/$1" | jq -r .object.sha
}

json_get() {
    jq -r "$1" < 'versions.json'
}

json_set() {
    jq --arg x "$2" "$1 = \$x" < 'versions.json' | sponge 'versions.json'
}

tag=$(get_latest)
version=${tag/v/}

msg "tag: $tag, version: $version"

[[ ${version} = $(json_get .version) ]] && { msg "${version} is up to date"; exit 0; }
sha=$(get_sha "${tag}")
sri=$(nix-prefetch --index 0 -E "koreader-from-src.overrideAttrs { version = \"${version}\"; }")

msg "sha: $sha, sri: $sri"

cd pkgs/additional/koreader-from-src
json_set ".version" "${version}"
json_set ".koreader.hash" "${sri}"

