#!/usr/bin/env bash

: <<'DOC'
Channel plugin for installing Go tools with `go install`.

Requirements:
  version   module version to install
  pkg       required Go module path
DOC

function __go_install__install() {
  local tool="$1"
  local requirements="$2"

  local version pkg
  version=$(jq_get "$requirements" '.version')
  pkg=$(jq_get "$requirements" '.pkg')

  if ! jq_defined "$pkg"; then
    error "go-install tool '$tool' requires a 'pkg' field in manifest"
    return 1
  fi

  if ! command -v go >/dev/null 2>&1; then
    error "go-install tool '$tool' requires Go on PATH (install the 'go' tool first)"
    return 1
  fi

  # shellcheck disable=SC2155
  export PATH="$(go env GOPATH)/bin:$PATH"
  go install "${pkg}@v${version}"
}

function __go_install__uninstall() {
  local tool="$1"
  local bin_path
  bin_path="$(command -v "$tool" 2>/dev/null || true)"

  if [[ -n "$bin_path" ]]; then
    rm -f "$bin_path"
  fi
}

register_channel \
  --name "go-install" \
  --installer __go_install__install \
  --uninstaller __go_install__uninstall \
  --dependency "go" \
  --dependency-default "$(jq_obj \
    '.channel' 'script' \
    '.version' '1.25.5'
  )"