#!/usr/bin/env bash

latest_download() (
	FILTER='import "github" as gh; gh::latest_download(env.OS; env.ARCH)'
	OS=${2} ARCH="${3}" jq --raw-output "${FILTER}" <"$(release_json "${1}")"
)

latest_type() (
	FILTER='import "github" as gh; gh::latest_type(env.OS; env.ARCH)'
	OS=${2} ARCH="${3}" jq --raw-output "${FILTER}" <"$(release_json "${1}")"
)

latest_version() (
	FILTER='import "github" as gh; gh::latest_version'
	jq --raw-output "${FILTER}" <"$(release_json "${1}")"
)

age_in_seconds() (
	echo $(($(date +"%s") - $(stat -c "%Y" "${1}")))
)

release_json() (
	DAY=$((60 * 60 * 24))
	PROJECT=$1
	JSON=${XDG_CACHE_HOME}/apps/meta/${PROJECT}/releases.json
	mkdir -p "$(dirname "${JSON}")"
	if [[ ! -f ${JSON} || "$(age_in_seconds "${JSON}")" -gt ${DAY} ]]; then
		curl --silent --output "${JSON}" "https://api.github.com/repos/${PROJECT}/releases"
	fi
	echo "${JSON}"
)