#!/usr/bin/env bash
set -euo pipefail

: "${RUNTIME_VERSION:?RUNTIME_VERSION required}"

RUNTIME="dotnet"
RUNTIME_ROOT="/opt/zlh/runtimes/${RUNTIME}"
DEST_DIR="${RUNTIME_ROOT}/${RUNTIME_VERSION}"
CURRENT_LINK="${RUNTIME_ROOT}/current"
ZLH_ARTIFACT_BASE_URL="${ZLH_ARTIFACT_BASE_URL:-http://zlh-artifacts.internal.zlh:8080}"
INSTALLER_URL="${ZLH_ARTIFACT_BASE_URL%/}/devcontainer/dotnet/dotnet-install.sh"
INSTALLER_TMP="/tmp/dotnet-install.sh"

log() {
  echo "[zlh-installer:${RUNTIME}] $*"
}

fail() {
  echo "[zlh-installer:${RUNTIME}] ERROR: $*" >&2
  exit 1
}

download_installer() {
  log "action=artifact_fetch step=download_installer url=${INSTALLER_URL} target=${INSTALLER_TMP}"
  if command -v curl >/dev/null 2>&1; then
    curl -fL "${INSTALLER_URL}" -o "${INSTALLER_TMP}"
  elif command -v wget >/dev/null 2>&1; then
    wget -O "${INSTALLER_TMP}" "${INSTALLER_URL}"
  else
    fail "curl or wget is required"
  fi
  chmod +x "${INSTALLER_TMP}"
  log "action=artifact_fetch step=download_installer status=ok url=${INSTALLER_URL} target=${INSTALLER_TMP}"
}

mkdir -p "${RUNTIME_ROOT}"

if [[ -d "${DEST_DIR}" ]]; then
  log "action=artifact_install runtime=${RUNTIME} version=${RUNTIME_VERSION} target=${DEST_DIR} status=already_installed"
else
  mkdir -p "${DEST_DIR}"
  download_installer
  log "action=artifact_install runtime=${RUNTIME} version=${RUNTIME_VERSION} target=${DEST_DIR} step=install status=begin"
  bash "${INSTALLER_TMP}" --channel "${RUNTIME_VERSION}" --install-dir "${DEST_DIR}"
fi

ln -sfn "${DEST_DIR}" "${CURRENT_LINK}"
cat >/etc/profile.d/zlh-dotnet.sh <<EOF
export PATH="${CURRENT_LINK}:\$PATH"
EOF
chmod +x /etc/profile.d/zlh-dotnet.sh
chmod -R 755 "${DEST_DIR}"
rm -f "${INSTALLER_TMP}"

log "action=artifact_install runtime=${RUNTIME} version=${RUNTIME_VERSION} target=${DEST_DIR} status=ok"
