#!/bin/bash
# omarchy:summary=Install or remove the OmarchyCN layer on an existing Omarchy
# omarchy:args=[--uninstall]
# omarchy:examples=omarchy-cn-install-overlay | omarchy-cn-install-overlay --uninstall
# Bootstraps onto a foreign OMARCHY_PATH, so it resolves its own checkout root.

set -euo pipefail

SRC=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
DEST="${OMARCHY_PATH:?OMARCHY_PATH must point at the target Omarchy install}"
MANIFEST="$HOME/.local/state/omarchycn/overlay-manifest"

run_dest() {
  if [[ -w $DEST ]]; then
    "$@"
  else
    sudo "$@"
  fi
}

uninstall() {
  if [[ ! -f $MANIFEST ]]; then
    echo "No overlay manifest at $MANIFEST" >&2
    exit 1
  fi
  while IFS= read -r rel; do
    [[ $rel == source=* ]] && continue
    run_dest rm -f "$DEST/$rel"
  done < "$MANIFEST"
  run_dest rm -rf "$DEST/cn"
  rm -f "$MANIFEST"
  echo "OmarchyCN overlay removed from $DEST"
}

install() {
  if [[ ! -f $DEST/version || ! -x $DEST/bin/omarchy ]]; then
    echo "No Omarchy install found at $DEST" >&2
    exit 1
  fi
  if [[ $SRC == "$DEST" ]]; then
    echo "Source checkout and target are the same tree; nothing to overlay" >&2
    exit 1
  fi

  mkdir -p "${MANIFEST%/*}"
  echo "source=$SRC" > "$MANIFEST"

  run_dest mkdir -p "$DEST/cn"
  run_dest cp -r "$SRC/cn/." "$DEST/cn/"

  local f rel
  for f in "$SRC/bin/omarchycn" "$SRC"/bin/omarchy-cn-*; do
    rel="bin/${f##*/}"
    run_dest cp "$f" "$DEST/$rel"
    echo "$rel" >> "$MANIFEST"
  done

  echo "OmarchyCN overlay installed into $DEST ($(grep -c '^bin/' "$MANIFEST") commands)"
  echo "Verify: omarchy cn version"
}

if [[ ${1:-} == "--uninstall" ]]; then
  uninstall
else
  install
fi
