#!/usr/bin/env bash

set -euo pipefail

die() {
  echo "Error: $*" >&2
  exit 1
}

command -v apt-get >/dev/null 2>&1 || die "this script requires an APT-based distribution."
if ((EUID == 0)); then
  sudo_cmd=()
elif command -v sudo >/dev/null 2>&1; then
  sudo_cmd=(sudo)
else
  die "run as root or install sudo."
fi

detected_arch="$(dpkg --print-architecture)"
[[ "$detected_arch" == "arm64" ]] || die "this script targets arm64; detected $detected_arch."

dotnet_channel="${DOTNET_CHANNEL:-LTS}"
dotnet_arch="arm64"
install_dir="/usr/local/share/dotnet"
profile_path="/etc/profile.d/dotnet.sh"

work_dir="$(mktemp -d)"
cleanup() {
  rm -rf -- "$work_dir"
}
trap cleanup EXIT

echo "Installing .NET runtime dependencies..."
"${sudo_cmd[@]}" apt-get update
"${sudo_cmd[@]}" apt-get install -y --no-install-recommends \
  ca-certificates curl libc6 libgcc-s1 libgssapi-krb5-2 libicu-dev \
  libssl3 libstdc++6 zlib1g

echo "Downloading Microsoft's .NET installer..."
curl -fsSL --retry 3 -o "$work_dir/dotnet-install.sh" https://dot.net/v1/dotnet-install.sh

echo "Installing the $dotnet_channel .NET SDK for $dotnet_arch..."
"${sudo_cmd[@]}" bash "$work_dir/dotnet-install.sh" \
  --channel "$dotnet_channel" \
  --architecture "$dotnet_arch" \
  --install-dir "$install_dir"

cat >"$work_dir/dotnet.sh" <<EOF
# .NET SDK system-wide environment
export DOTNET_ROOT="$install_dir"
export PATH="\$DOTNET_ROOT:\$DOTNET_ROOT/tools:\$PATH"
EOF
"${sudo_cmd[@]}" install -o root -g root -m 0644 "$work_dir/dotnet.sh" "$profile_path"

echo ".NET SDK installation completed. Log in again to load $profile_path."
"$install_dir/dotnet" --version
