#!/bin/bash
# omarchy:summary=Update an overlay install: pull source, reinstall, run migrations
# omarchy:examples=omarchycn update

set -euo pipefail

MANIFEST="$HOME/.local/state/omarchycn/overlay-manifest"
MIGRATION_STATE="$HOME/.local/state/omarchycn/last-migration"

if [[ ! -f $MANIFEST ]]; then
  echo "Not an overlay install (no $MANIFEST)." >&2
  echo "Package-based installs update through 'omarchy update' / pacman." >&2
  exit 1
fi

src=$(grep -m1 '^source=' "$MANIFEST" | cut -d= -f2-)
if [[ ! -d $src/.git ]]; then
  echo "Overlay source $src is not a git checkout" >&2
  exit 1
fi

old=$(git -C "$src" rev-parse --short HEAD)
git -C "$src" pull --ff-only
new=$(git -C "$src" rev-parse --short HEAD)
echo "Source: $old -> $new"

"$src/bin/omarchy-cn-install-overlay"

# Run migrations newer than the last recorded one, in filename order
last=""
if [[ -f $MIGRATION_STATE ]]; then
  last=$(<"$MIGRATION_STATE")
fi

if [[ -d $src/cn/migrations ]]; then
  for m in "$src"/cn/migrations/*.sh; do
    [[ -f $m ]] || continue
    name="${m##*/}"
    if [[ $name > $last ]]; then
      echo "Migration: $name"
      bash "$m"
      echo "$name" > "$MIGRATION_STATE"
    fi
  done
fi

echo "OmarchyCN update complete ($(omarchy-cn-version 2>/dev/null || echo unknown))"
