#!/bin/bash

# omarchy:summary=Update the active Omarchy dev checkout

set -euo pipefail

[[ $OMARCHY_PATH != "/usr/share/omarchy" ]] || exit 0

if ! git -C "$OMARCHY_PATH" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "Error: OMARCHY_PATH is not a git checkout: $OMARCHY_PATH" >&2
  exit 1
fi

upstream=$(git -C "$OMARCHY_PATH" rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null || true)
if [[ -z $upstream ]]; then
  echo -e "\e[33m\nSkip Omarchy dev checkout update (current branch has no upstream)\e[0m"
  exit 0
fi

echo -e "\e[32m\nUpdate Omarchy dev checkout\e[0m"
# A filtered fetch makes a full clone blobless once; git saves the filter, so
# pulls then only fetch the file contents the new checkout needs.
remote=$(git -C "$OMARCHY_PATH" for-each-ref --format='%(upstream:remotename)' "$(git -C "$OMARCHY_PATH" symbolic-ref -q HEAD)")
if git -C "$OMARCHY_PATH" config "remote.$remote.url" >/dev/null && ! git -C "$OMARCHY_PATH" config "remote.$remote.promisor" >/dev/null; then
  git -C "$OMARCHY_PATH" fetch --filter=blob:none "$remote"
fi
git -C "$OMARCHY_PATH" pull --ff-only
