#!/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_DONE_DIR="$HOME/.local/state/omarchycn/migrations-done"

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 each not-yet-completed migration in filename order, one marker per file
if [[ -d $src/cn/migrations ]]; then
  mkdir -p "$MIGRATION_DONE_DIR"
  for m in "$src"/cn/migrations/*.sh; do
    [[ -f $m ]] || continue
    name="${m##*/}"
    if [[ ! -f $MIGRATION_DONE_DIR/$name ]]; then
      echo "Migration: $name"
      bash -euo pipefail "$m"
      touch "$MIGRATION_DONE_DIR/$name"
    fi
  done
fi

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