#!/usr/bin/env bash

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

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

function __cargo_install__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 install "$crate" --version "$version" $args
}

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

  cargo uninstall -v "$crate"
}

register_channel \
  --name "cargo-install" \
  --installer __cargo_install__install \
  --uninstaller __cargo_install__uninstall \
  --dependency "rustup" \
  --dependency-default "$(jq_obj \
    '.channel' 'script' \
    '.version' '1.28.2' \
    '.needs' '["build-essential"]'
  )"
