#!/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

channel=$(omarchy-cn-channel)
channel=${channel%% *}

old=$(git -C "$src" rev-parse --short HEAD)
git -C "$src" fetch -q --tags origin

case "$channel" in
nightly)
  git -C "$src" checkout -q quattro
  git -C "$src" pull --ff-only origin quattro
  ;;
beta)
  tag=$(git -C "$src" tag -l "*-cn.*" | sort -V | tail -1)
  if [[ -z $tag ]]; then
    echo "beta 通道无可用发布 tag" >&2
    exit 1
  fi
  git -C "$src" checkout -q "$tag"
  ;;
stable)
  tag=$(git -C "$src" tag -l "*-cn.*" | grep -vE "alpha|beta|rc" | sort -V | tail -1 || true)
  if [[ -z $tag ]]; then
    echo "当前尚无 stable 发布（omarchycn channel beta 可跟随预发布）" >&2
    exit 1
  fi
  git -C "$src" checkout -q "$tag"
  ;;
*)
  echo "Unknown channel: $channel" >&2
  exit 1
  ;;
esac

# Never move onto a tree that predates the channel mechanism: its update
# command cannot switch back, stranding the install
if [[ ! -f $src/bin/omarchy-cn-channel ]]; then
  git -C "$src" checkout -q "$old"
  echo "$channel 通道的目标发布早于通道机制，已回退；请使用 nightly 或更新的发布" >&2
  exit 1
fi

new=$(git -C "$src" rev-parse --short HEAD)
echo "Channel: $channel, 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))"
