#!/usr/bin/env bash
# shellcheck disable=SC2016

set -euo pipefail

plugins=$(< sources.json)

q() {
  jq -r "$@" <<<"$plugins"
}

u() {
  plugins=$(jq "$@" <<<"$plugins")
}

update_plugin() {
  name=$1
  branch=$(q --arg name "$name" '.[$name].branch // "HEAD"')

  echo "Updating $name" >&2
  revision=$(git ls-remote "https://github.com/$name" "$branch" | cut -b -40)
  sha256=$(nix-prefetch-url --unpack "https://github.com/$name/archive/$revision.tar.gz")

  u --arg name "$name" --arg rev "$revision" --arg sha256 "$sha256" '
    .[$name] = (.[$name] // {}) * {
      rev: $rev,
      sha256: $sha256,
    }
  '
}

update_all() {
  for plugin in $(q 'to_entries | .[] | .key'); do
    update_plugin "$plugin"
  done
}

if [ "$#" -eq 0 ]; then
  update_all
else
  while [ "$#" -gt 0 ]; do
    update_plugin "$1"
    shift
  done
fi

echo "$plugins" > sources.json