#!/usr/bin/env nix-shell
#!nix-shell -i bash -p nix-update yq

set -euo pipefail

nix-update "${UPDATE_NIX_ATTR_PATH}"

src="$(nix-build -A "${UPDATE_NIX_ATTR_PATH}".src --no-out-link)"

(
  echo "# This file has been autogenerated by update.sh"
  echo "# Do not edit this file manually."

  echo "{"

  yq -r '.[]|[.name, .version] | @tsv' < "${src}/scripts/plugin/plugin.yaml" \
  | while IFS=$'\t' read -r name version; do
    echo "  \"${name}\" = {"

    echo "    version = \"${version}\";"

    url="https://github.com/perses/plugins/releases/download/${name,,}/v${version}/${name}-${version}.tar.gz"
    echo "    url = \"${url}\";"

    hash="$(nix-prefetch-url "${url}" --name "${UPDATE_NIX_PNAME}-${name,,}-${version}.tar.gz")"
    hash="$(nix --extra-experimental-features nix-command hash convert --hash-algo sha256 "${hash}")"

    echo "    hash = \"${hash}\";"

    echo "  };"
  done

  echo "}"
) > "$(dirname "${BASH_SOURCE[0]}")/plugins.nix"

