#!/usr/bin/env bash

# omarchy:summary=Install the latest version of an asdf tool and set it in ~/.tool-versions
# omarchy:args=<plugin> [version-prefix]
# omarchy:hidden=true

# Based: the one asdf step every development row takes, on Debian and on
# macOS. On Debian the plugin comes only through the asdf package's
# asdf-plugin-add, from the reviewed bundle it ships, which refuses a plugin it
# does not list; asdf plugin add and update are never called there, since the
# shipped commit is no ref they can fetch. On macOS brew's asdf ships no bundle,
# so a plugin comes from asdf's own index, or from its own repository where the
# index does not carry it: the review copies Based publishes on gitlab.com and
# the two plugins whose index entries point at archived projects. Then asdf
# installs the latest version, narrowed by a prefix when one is given
# (java openjdk), and sets it in ~/.tool-versions.

set -eo pipefail

plugin=${1:-}
prefix=${2:-}

if [[ -z $plugin ]]; then
  echo "Usage: omarchy-dev-env-tool <plugin> [version-prefix]" >&2
  exit 1
fi

asdf_data=${ASDF_DATA_DIR:-$HOME/.asdf}
export PATH="$asdf_data/shims:$PATH"

plugin_repository() {
  case $1 in
  cloudmonkey | hcloud | mongosh | ovhcloud | solana | sui) echo "https://gitlab.com/based-linux/asdf/asdf-$1.git" ;;
  dotnet) echo https://github.com/hensou/asdf-dotnet.git ;;
  foundry) echo https://github.com/llllvvuu/asdf-foundry.git ;;
  esac
}

if [[ $(omarchy-os) == darwin ]]; then
  if [[ ! -d $asdf_data/plugins/$plugin ]]; then
    repository=$(plugin_repository "$plugin")
    asdf plugin add "$plugin" ${repository:+"$repository"}
  fi
else
  /usr/lib/based/asdf-plugin-add "$plugin"
fi

version=$(asdf latest "$plugin" ${prefix:+"$prefix"})
asdf install "$plugin" "$version"
asdf set --home "$plugin" "$version"
