#!/usr/bin/env bash

# This is a script called by multiple tests to find the runtime id of
# the current platform.

set -euo pipefail

SCRIPT_PATH=$(realpath $0)
SCRIPT_DIR=$(dirname "$SCRIPT_PATH")

function usage() {
    echo "usage: $0 [--portable] [--sdk]"
    echo ""
    echo "Prints a rid for the current environment"
    echo ""
    echo "$0              prints the non-portable rid for the OS"
    echo "$0 --portable   prints the portable rid for the OS"
    echo "$0 --sdk        prints the rid the SDK was built for"
}

portable_rid=0
sdk_rid=0
while [[ $# -gt 0 ]]; do
    arg=$1
    shift
    case "$arg" in
        --portable) portable_rid=1 ;;
        --sdk)      sdk_rid=1 ;;
        *) usage; exit 1 ;;
    esac
done

if [[ ${sdk_rid} == 1 ]]; then
  sdk_dir=$("$SCRIPT_DIR/dotnet-directory" --sdk)
  rid_line=$(grep -m 1 "<NETCoreSdkRuntimeIdentifier>" "$sdk_dir/Microsoft.NETCoreSdk.BundledVersions.props")
  rid_regex="<NETCoreSdkRuntimeIdentifier>(.*)</NETCoreSdkRuntimeIdentifier>"
  if [[ "$rid_line" =~ $rid_regex ]]; then
      sdk_rid="${BASH_REMATCH[1]}"
  else
    echo "failed to parse id from: '$rid_line'"
    exit 1
  fi
  echo $sdk_rid
  exit 0
fi

source /etc/os-release

declare -A archmap
archmap=(
    ["aarch64"]="arm64"
    ["amd64"]="x64"
    ["armv8l"]="arm"
    ["i686"]="x86"
    ["i386"]="x86"
    ["x86_64"]="x64"
    ["s390x"]="s390x"
    ["ppc64le"]="ppc64le"
)

arch=${archmap["$(uname -m)"]}

if [[ ${portable_rid} == 1 ]]; then
    if (ldd --version 2>&1 || true) | grep -q musl ; then
        echo "linux-musl-${arch}"
    else
        echo "linux-${arch}"
    fi
else
    case "${ID}" in
        # Remove the minor version
        alma|ol|rhel|rocky)
            rid_version=${VERSION_ID%.*}
            ;;
        alpine)
            # Remove _ and extra . to compute just the major.minor version
            rid_version=$(echo "$VERSION_ID" | cut -d'_' -f1 | cut -d'.' -f1-2)
            ;;

        *)
            rid_version=${VERSION_ID}
            ;;
    esac

    echo "${ID}.${rid_version}-${arch}"
fi
