#!/usr/bin/env bash

: <<'DOC'
Channel plugin for installing Rust crates with `cargo binstall`.

Requirements:
  version   crate version to install
  crate     optional crate name override
  args      optional extra arguments passed to `cargo binstall`
DOC

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

  local version crate args
  version=$(jq_get "$requirements" '.version')
  crate=$(jq_get "$requirements" '.crate' "$tool")
  args=$(jq_get "$requirements" '.args')

  if ! jq_defined "$args"; then
    args=""
  fi

  # shellcheck disable=SC2086
  cargo binstall -y $args "${crate}@${version}"
}

function __cargo_binstall__uninstall() {
  local tool="$1"
  local requirements="$2"
  local crate
  crate=$(jq_get "$requirements" '.crate' "$tool")

  cargo uninstall -v "$crate"
}

register_channel \
  --name "cargo-binstall" \
  --installer __cargo_binstall__install \
  --uninstaller __cargo_binstall__uninstall \
  --dependency "cargo-binstall" \
  --dependency-default "$(jq_obj \
    '.channel' 'cargo-install' \
    '.version' '1.18.0' \
    '.crate' 'cargo-binstall'
  )"