#!/bin/bash
# omarchy:summary=Revert an OmarchyCN conversion back to vanilla Omarchy
# omarchy:examples=omarchy cn revert
# Curl-able and self-deleting-safe: main() is fully parsed before the package
# swap removes this file from the cn tree it may be running from.

set -euo pipefail

STATE_DIR=/var/lib/omarchycn
STATE=$STATE_DIR/convert-state
MIRROR_LINE="Server = https://git.zacharyzhang.com/api/packages/ZacharyZhang-NY/arch/omarchy/x86_64"
REG_KEY_FPR=74DCF57ACD812B24D959F146BD386048867B33B4
# Bootstrap exception: curl|bash runs outside a session, so default the path
export OMARCHY_PATH=${OMARCHY_PATH:-/usr/share/omarchy}

main() {
  if [[ ! -f $STATE ]]; then
    echo "未发现转换状态（$STATE）：本机不是由 omarchy cn convert 转换而来" >&2
    exit 1
  fi
  if (( EUID == 0 )); then
    echo "请以普通用户运行（脚本内部按需 sudo）" >&2
    exit 1
  fi

  local prev_omarchy="" prev_settings="" new_pkgs=""
  # State is trusted root-owned key=value lines written by convert
  source "$STATE"
  [[ -n $prev_omarchy && -n $prev_settings ]] || { echo "转换状态损坏: $STATE" >&2; exit 1; }

  echo "==> 清理转换时播种的用户配置（与 cn 层原件一致才删除）"
  local seeded
  for seeded in \
    "$HOME/.config/fcitx5/profile:/usr/share/omarchy/cn/fcitx5/profile" \
    "$HOME/.config/fontconfig/conf.d/64-omarchycn-cjk.conf:/usr/share/omarchy/cn/fontconfig/64-omarchycn-cjk.conf"; do
    if cmp -s "${seeded%%:*}" "${seeded#*:}" 2> /dev/null; then
      rm -f "${seeded%%:*}"
    fi
  done

  echo "==> 还原 mirrorlist 与系统语言"
  sudo cp "$STATE_DIR/mirrorlist.pre" /etc/pacman.d/mirrorlist
  if [[ -f $STATE_DIR/locale.conf.pre ]]; then
    sudo cp "$STATE_DIR/locale.conf.pre" /etc/locale.conf
  fi

  echo "==> pacman.conf 移除 [omarchycn] 与 [omarchy] 镜像行"
  sudo sed -i "\|^$MIRROR_LINE\$|d" /etc/pacman.conf
  # Delete the section header and body, but keep any section that follows
  sudo sed -i '/^\[omarchycn\]$/,/^\[/{ /^\[omarchycn\]$/d; /^\[/!d; }' /etc/pacman.conf

  echo "==> 换回上游软件包（$prev_omarchy/$prev_settings）"
  sudo pacman -Sy
  # --ask=4 auto-confirms removing the conflicting cn packages
  sudo pacman -S --noconfirm --ask=4 "omarchy/$prev_omarchy" "omarchy/$prev_settings"
  if [[ -n $new_pkgs ]]; then
    # Only what is still installed: a user may have removed some already,
    # and a -R failure here would strand the swap-completed system
    local p still=""
    for p in $new_pkgs; do
      # grep without -q consumes the whole list: -q's early exit would
      # SIGPIPE pacman and read as "not installed" under pipefail
      pacman -Qq | grep -xF "$p" > /dev/null && still+="$p "
    done
    if [[ -n $still ]]; then
      echo "==> 移除转换时新装的包: ${still% }"
      # shellcheck disable=SC2086
      sudo pacman -R --noconfirm ${still% }
    fi
  fi

  echo "==> 移除 registry 公钥信任"
  sudo pacman-key --delete "$REG_KEY_FPR" > /dev/null 2>&1 || true

  # The system is vanilla again: clear state before the cosmetic tail so a
  # plymouth failure cannot strand a reverted machine in "converted" state
  systemctl --user restart omarchy-fcitx5.service 2> /dev/null || true
  sudo rm -rf "$STATE_DIR"

  echo "==> 还原上游开机画面"
  if ! omarchy-refresh-plymouth; then
    echo "开机画面还原失败：手动执行 omarchy-refresh-plymouth 即可" >&2
    exit 1
  fi
  echo
  echo "已回退为原版 Omarchy（重新登录生效）。再次转换: omarchy cn convert"
}

main "$@"
