#!/usr/bin/env bash

set -euo pipefail

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

if ((EUID == 0)); then
  die "run this current-user installer without sudo."
fi
command -v apt-get >/dev/null 2>&1 || die "this script requires an APT-based distribution."
command -v sudo >/dev/null 2>&1 || die "sudo is required to install runtime dependencies."

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="$HOME/.dotnet"

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

echo "Installing .NET runtime dependencies..."
sudo apt-get update
sudo 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..."
bash "$work_dir/dotnet-install.sh" \
  --channel "$dotnet_channel" \
  --architecture "$dotnet_arch" \
  --install-dir "$install_dir"

if [[ -n "${PROFILE_FILE:-}" ]]; then
  profile_file="$PROFILE_FILE"
else
  case "${SHELL:-}" in
    */zsh) profile_file="$HOME/.zshrc" ;;
    */bash) profile_file="$HOME/.bashrc" ;;
    *) profile_file="$HOME/.profile" ;;
  esac
fi

touch "$profile_file"
if ! grep -Fqx '# >>> dotnet SDK >>>' "$profile_file"; then
  cat >>"$profile_file" <<'EOF'

# >>> dotnet SDK >>>
export DOTNET_ROOT="$HOME/.dotnet"
export PATH="$DOTNET_ROOT:$DOTNET_ROOT/tools:$PATH"
# <<< dotnet SDK <<<
EOF
fi

echo ".NET SDK installation completed."
echo "Restart your shell or run: source \"$profile_file\""
"$install_dir/dotnet" --version
