#!/bin/bash

set -ex

gpg --keyserver keys.openpgp.org --recv EB114F5E6C0DC2BCDD183550A4B61A2DC5923710

JSON=$(wget -q 'https://codeberg.org/api/v1/repos/forgejo/forgejo/releases?draft=false&pre-release=false&limit=1' --header 'accept: application/json' -O -)
VERS=$(echo $JSON| jq -r '.[0].name')

mkdir -p ~/forgejo/

if [ ! -f ~/"forgejo/forgejo-$VERS-linux-amd64.xz" ]; then
    rm -rf ~/"forgejo/forgejo-*-linux-amd64.xz"
    wget $(echo $JSON | jq -r '.[0].assets | map(select(.name | endswith("linux-amd64.xz"))) | .[0].browser_download_url') -O ~/"forgejo/forgejo-$VERS-linux-amd64.xz"
fi
if [ ! -f ~/"forgejo/forgejo-$VERS-linux-amd64.xz.asc" ]; then
    rm -rf ~/"forgejo/forgejo-*-linux-amd64.xz.asc"
    wget $(echo $JSON | jq -r '.[0].assets | map(select(.name | endswith("linux-amd64.xz.asc"))) | .[0].browser_download_url') -O ~/"forgejo/forgejo-$VERS-linux-amd64.xz.asc"
fi

gpg --verify ~/"forgejo/forgejo-$VERS-linux-amd64.xz.asc" ~/"forgejo/forgejo-$VERS-linux-amd64.xz"

cp -a ~/"forgejo/forgejo-$VERS-linux-amd64.xz" .
xz -d "forgejo-$VERS-linux-amd64.xz"
mv "forgejo-$VERS-linux-amd64" "$IMAGE_NAME_RISOTTO_IMAGE_DIR_TMP/usr/bin/forgejo"
chmod +x "$IMAGE_NAME_RISOTTO_IMAGE_DIR_TMP/usr/bin/forgejo"
