#!/bin/bash
# omarchy:summary=Full OmarchyCN update: system, cn data, and migrations
# omarchy:examples=omarchycn update

set -euo pipefail

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

if [[ ! -f $MANIFEST ]]; then
  # Package install: the pipeline brings the new cn tree and runs cn migrations
  if [[ -d $OMARCHY_PATH/cn ]]; then
    exec omarchy-update
  fi
  echo "未检测到 OmarchyCN（$OMARCHY_PATH/cn 不存在，也没有 overlay manifest）" >&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 or migrate mechanism:
# it cannot switch back or finish this update's migration step
if [[ ! -f $src/bin/omarchy-cn-channel || ! -f $src/bin/omarchy-cn-migrate ]]; 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"

"$src/bin/omarchy-cn-migrate"

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