#!/bin/sh
# Installs or updates devop-dk. Needs only the .NET 10 runtime. Usage: install.sh [version]
# One line: curl -fsSL https://wiki.devop.is/devop-dk/install.sh | sh   (pin: ... | sh -s -- 0.13.2)
# DEVOP_DK_NUPKG=<file> installs from a local package instead of NuGet.org.
set -eu
base=https://api.nuget.org/v3-flatcontainer/devop.dk.plus.cli
dest=${XDG_DATA_HOME:-$HOME/.local/share}/devop-dk
bin=$HOME/.local/bin
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
pkg=${DEVOP_DK_NUPKG:-}
if [ -z "$pkg" ]; then
  v=${1:-$(curl -fsSL "$base/index.json" | grep -o '"[0-9][0-9.]*"' | tr -d '"' | sort -V | tail -n 1)}
  [ -n "$v" ] || { echo "Could not find a devop-dk version on NuGet.org." >&2; exit 1; }
  pkg=$tmp/devop-dk.nupkg
  curl -fsSL -o "$pkg" "$base/$v/devop.dk.plus.cli.$v.nupkg"
fi
unzip -q -o "$pkg" 'tools/net10.0/any/*' -d "$tmp/x"
[ -f "$tmp/x/tools/net10.0/any/devop-dk" ] || {
  echo "This package has no portable launcher; portable installs need devop-dk 0.13.2 or later." >&2; exit 1; }
other=$(command -v devop-dk 2>/dev/null || true)
rm -rf "$dest"; mkdir -p "$dest" "$bin"
cp -R "$tmp/x/tools/net10.0/any/." "$dest"
chmod +x "$dest/devop-dk"
ln -sf "$dest/devop-dk" "$bin/devop-dk"
echo "Installed devop-dk to $dest (linked $bin/devop-dk)."
if [ -n "$other" ] && [ "$other" != "$bin/devop-dk" ]; then
  echo "Warning: another devop-dk is on PATH ($other) and may shadow this one." >&2
fi
case ":$PATH:" in *":$bin:"*) ;; *)
  echo "Add it to PATH:  export PATH=\"$bin:\$PATH\"" ;;
esac
command -v dotnet >/dev/null 2>&1 || {
  echo "The .NET 10 runtime (not the SDK) is still needed:" >&2
  echo "  Ubuntu/Debian:  sudo apt-get install -y dotnet-runtime-10.0" >&2
  echo "  Other systems:  https://dotnet.microsoft.com/download/dotnet/10.0" >&2; }
exit 0
