#!/usr/bin/env bash
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$root"

if [[ ! -f .gitmodules ]] || ! git config --file .gitmodules --get submodule.cordis.path >/dev/null; then
  echo 'Cordis submodule is not configured.' >&2
  exit 1
fi

git submodule sync -- cordis
git submodule update --init cordis

if [[ -n "$(git -C cordis status --porcelain)" ]]; then
  echo 'Cordis has local changes. Commit, stash, or discard them before updating.' >&2
  exit 1
fi

git -C cordis fetch --prune origin main
if git -C cordis show-ref --verify --quiet refs/heads/main; then
  git -C cordis switch main
else
  git -C cordis switch --track -c main origin/main
fi

git -C cordis merge --ff-only origin/main

echo "Cordis updated to $(git -C cordis rev-parse --short HEAD)."
echo 'Commit the updated cordis gitlink in this repository to share the new pin.'
