#!/bin/sh

set -eu

# External plugin pins to refresh. Each name maps to ../tribes-plugin-$name
# and tribes/plugins/$name.scm unless update-plugin-pin is called with
# different defaults in the future.
plugins="sender aether supertest kobold trust"

usage() {
  cat <<'EOF'
Usage: update-tribes-and-plugin-pins [options]

Refresh the Tribes pin and all plugin pins listed in this script by calling
scripts/update-tribes-pin and scripts/update-plugin-pin.

Options:
  --commit             Commit the affected pin files after updating
  --tribes-repo PATH   Local Tribes git checkout
  --guix-repo PATH     Local guix-tribes checkout
  --build-host HOST       SSH host used by the update scripts for Guix builds and hashing
  -h, --help           Show this help
EOF
}

script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
default_guix_repo=$(CDPATH= cd -- "$script_dir/.." && pwd)
default_tribes_repo=$(CDPATH= cd -- "$default_guix_repo/../tribes" && pwd)

guix_repo=$default_guix_repo
tribes_repo=$default_tribes_repo
build_host=
commit_after=false

while [ "$#" -gt 0 ]; do
  case "$1" in
    --commit)
      commit_after=true
      shift
      ;;
    --tribes-repo)
      tribes_repo=$2
      shift 2
      ;;
    --guix-repo)
      guix_repo=$2
      shift 2
      ;;
    --build-host)
      build_host=$2
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      printf 'Unknown option: %s\n' "$1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

update_tribes_pin=$guix_repo/scripts/update-tribes-pin
update_plugin_pin=$guix_repo/scripts/update-plugin-pin

if [ ! -x "$update_tribes_pin" ]; then
  printf 'update-tribes-pin not found or not executable: %s\n' "$update_tribes_pin" >&2
  exit 1
fi

if [ ! -x "$update_plugin_pin" ]; then
  printf 'update-plugin-pin not found or not executable: %s\n' "$update_plugin_pin" >&2
  exit 1
fi

build_host_args=
if [ -n "$build_host" ]; then
  build_host_args="--build-host $build_host"
fi

# shellcheck disable=SC2086
"$update_tribes_pin" \
  --guix-repo "$guix_repo" \
  --tribes-repo "$tribes_repo" \
  $build_host_args

for plugin in $plugins; do
  # shellcheck disable=SC2086
  "$update_plugin_pin" \
    --guix-repo "$guix_repo" \
    --tribes-repo "$tribes_repo" \
    $build_host_args \
    "$plugin"
done

if [ "$commit_after" = true ]; then
  git -C "$guix_repo" add -- \
    tribes/packages/source.scm

  for plugin in $plugins; do
    git -C "$guix_repo" add -- "tribes/plugins/$plugin.scm"
  done

  if git -C "$guix_repo" diff --cached --quiet; then
    printf 'No pin changes to commit.\n'
  else
    git -C "$guix_repo" commit \
      -m "chore: Bump Tribes and plugin pins" \
      -m "Refresh the Tribes source pin and the external plugin pins listed in scripts/update-tribes-and-plugin-pins."
  fi
fi
