#!/bin/bash

set -e

export ZSTD_CLEVEL=19
export ZSTD_NBTHREADS="$(nproc)"

pub=/srv/msys2repo
staging=/home/repo/staging

SIGNWITHKEY=()
if [ -n "${GPGKEY}" ]
then
    SIGNWITHKEY=(-u "${GPGKEY}")
    gpg --recv-key "0x${GPGKEY}"
fi
gpg --detach-sign "${SIGNWITHKEY[@]}" "${0}"
rm "${0}.sig"

update_packages() {
    local repo="${1}"
    shift
    local path="${1}"
    shift

    local pkgs=("${@}")

    if [ "${#pkgs[@]}" -gt 0 ]
    then
        echo "==> ${path}"
        mkdir -p "${staging}/${path}/"
        cp "${pub}/${path}/${repo}".{db,files}{,.tar.zst}{,.sig} "${staging}/${path}/"
        repo-remove -s -v "${staging}/${path}/${repo}.db.tar.zst" "${pkgs[@]}"
        zstd --quiet --test "${staging}/${path}/${repo}.db.tar.zst"
        zstd --quiet --test "${staging}/${path}/${repo}.files.tar.zst"
        gpg --verify "${staging}/${path}/${repo}.db.tar.zst.sig" "${staging}/${path}/${repo}.db.tar.zst"
        gpg --verify "${staging}/${path}/${repo}.files.tar.zst.sig" "${staging}/${path}/${repo}.files.tar.zst"
        mv "${staging}/${path}/${repo}".{db,files}{,.tar.zst}{,.sig} "${pub}/${path}/"
        echo
    fi
}

repo="${1}"
shift
if [ "${repo}" = "mingw64" ]
then
    update_packages mingw64 "mingw/mingw64" "${@}"
elif [ "${repo}" = "mingw32" ]
then
    update_packages mingw32 "mingw/mingw32" "${@}"
elif [ "${repo}" = "ucrt64" ]
then
    update_packages ucrt64 "mingw/ucrt64" "${@}"
elif [ "${repo}" = "clang64" ]
then
    update_packages clang64 "mingw/clang64" "${@}"
elif [ "${repo}" = "clang32" ]
then
    update_packages clang32 "mingw/clang32" "${@}"
elif [ "${repo}" = "clangarm64" ]
then
    update_packages clangarm64 "mingw/clangarm64" "${@}"
elif [ "${repo}" = "mingwarm64" ]
then
    update_packages mingwarm64 "mingw/mingwarm64" "${@}"
elif [ "${repo}" = "msys" ]
then
    update_packages msys "msys/x86_64" "${@}"
else
    echo "Missing or unrecognized first argument: msys|mingw32|mingw64|ucrt64|clang64|clang32|clangarm64|mingwarm64" >&2
    exit 1
fi

date +%s > "${pub}/lastupdate"
