#!/usr/bin/env bash


# Copyright 1999-2023 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2


export PATH
trap 'exit 128' INT


case "${1}" in
    "" | -h | --help )
        echo "Usage: ${0} DOTNET_PROJECT DOTNET_COMPAT [DOTNET_EXECUTABLE]"
        ;;
esac


export DOTNET_CLI_TELEMETRY_OPTOUT=1
export DOTNET_NOLOGO=1
export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
export MSBUILDDISABLENODEREUSE=1
export UseSharedCompilation=false


dotnet_project="${1}"
DOTNET_COMPAT="${2}"
dotnet_executable="${3}"

cache_dir="$(pwd)/.cache"

nugets_txt="${cache_dir}/nugets.txt"

export NUGET_PACKAGES="${cache_dir}/nuget_packages"


if [[ -n "${dotnet_executable}" ]] ; then
    :
elif type -P "dotnet-${DOTNET_COMPAT}" ; then
    dotnet_executable="dotnet-${DOTNET_COMPAT}"
elif type -P "dotnet-bin-${DOTNET_COMPAT}" ; then
    dotnet_executable="dotnet-bin-${DOTNET_COMPAT}"
else
    echo " * Error: No suitable dotnet executable found."
    exit 1
fi

echo " * DOTNET_COMPAT: ${DOTNET_COMPAT}"
echo " * DOTNET_EXECUTABLE: ${dotnet_executable}"
echo " * NUGET_PACKAGES: ${NUGET_PACKAGES}"


passed_restores=""
failed_restores=""

for runtime in linux linux-{,musl-}{arm,arm64,x64,x86} ; do
    echo ">>> Restore for runtime: ${runtime}"

    if ${dotnet_executable} restore --force-evaluate --runtime "${runtime}" "${dotnet_project}" ; then
        passed_restores="${passed_restores} ${runtime}"
    else
        failed_restores="${passed_restores} ${runtime}"
    fi
done


pushd "${NUGET_PACKAGES}" || exit 1

for nuget in */* ; do
    echo "${nuget}" | sed "s#/#@#" >> "${nugets_txt}"
done

popd || exit 1


echo
echo " * Passed restores: ${passed_restores}"
echo " * Failed restores: ${failed_restores}"
echo


echo
echo "NUGETS:"

cat "${nugets_txt}"
echo
