#!/bin/sh
# This script uses sh instead of bash to be compatible with as many distros as possible.
set -u

# The script is located in the Rancher Desktop resources/ directory.
resources_dir=$(dirname "$0")

# We run setup-spin in the rancher-desktop distro to setup spin on the Win32 host.
if [ "${WSL_DISTRO_NAME:-}" = "rancher-desktop" ]; then
  spin="${resources_dir}/win32/bin/spin.exe"
elif [ "$(uname)" = "Linux" ]; then
  spin="${resources_dir}/linux/bin/spin"
else
  spin="${resources_dir}/darwin/bin/spin"
fi

if [ ! -x "$spin" ]; then
  echo "Cannot execute '${spin}' (or does not exist)"
  exit 1
fi

if [ "${WSL_DISTRO_NAME:-}" = "rancher-desktop" ]; then
  echo "Waiting for github.com to become resolvable"
  for _ in $(seq 30); do
    curl --head --silent http://github.com >/dev/null
    rc=$?; test $rc -ne 0 && echo "curl exit status is $rc"
    if [ $rc -ne 6 ]; then
      break
    fi
    sleep 2
  done
fi

install_templates() {
  repo=$1

  echo "Installing ${repo} templates from tag ${SPIN_TEMPLATES_TAG}"
  url="https://github.com/spinframework/${repo}/archive/refs/tags/${SPIN_TEMPLATES_TAG}.tar.gz"
  if ! "$spin" templates install --update --tar "$url"; then
    echo "Install failed, falling back to main branch"
    url="https://github.com/spinframework/${repo}/archive/refs/heads/main.tar.gz"
    "$spin" templates install --update --tar "$url"
  fi
}

install_plugin() {
  plugin=$1
  version=$2
  echo "Installing plugin ${plugin} version ${version}"
  "$spin" plugins uninstall "$plugin" || true
  # `spin plugins install` requires `git`; however, we can provide the URL of a
  # remote manifest instead.
  local url_base="https://github.com/spinframework/spin-plugins/raw/refs/heads/main/manifests/${plugin}"
  local url="${url_base}/${plugin}@${version}.json"
  if ! curl --head --silent --fail "${url}" &>/dev/null; then
    echo "Plugin not available at ${url}, installing unversioned instead."
    url="${url_base}/${plugin}.json"
  fi
  "$spin" plugins install --yes --url "${url}"
  rc=$?; test $rc -ne 0 && echo "Exit status is $rc"
}

install_templates spin
install_templates spin-python-sdk
install_templates spin-js-sdk

install_plugin kube "${KUBE_PLUGIN_VERSION:-0.3.1}"

echo "'${spin}' setup complete"
