#!/usr/bin/env bash
# MaQuanIME Linux installer: detect the active user's framework, never replace it.
set -euo pipefail

die() { printf '错误：%s\n' "$*" >&2; exit 1; }
usage() {
    printf '%s\n' '用法：bash install-maquan-linux.sh [--framework auto|fcitx4|fcitx5|ibus] [--dry-run]' \
        '只支持 x86_64。Fcitx4 提供 DEB；Fcitx5/IBus 提供 DEB/RPM。' \
        '自动检测不清时停止，请在日常登录用户的桌面终端运行，或明确指定框架。'
}

detect_framework() {
    local uid=${SUDO_UID:-$(id -u)} name
    local -a active=() installed=()
    for name in fcitx fcitx5 ibus-daemon; do
        if command -v pgrep >/dev/null && pgrep -u "$uid" -x "$name" >/dev/null 2>&1; then
            case "$name" in fcitx) active+=(fcitx4);; fcitx5) active+=(fcitx5);; *) active+=(ibus);; esac
        fi
    done
    if [ "${#active[@]}" -eq 1 ]; then printf '%s\n' "${active[0]}"; return; fi
    [ "${#active[@]}" -eq 0 ] || return 1
    command -v fcitx >/dev/null && installed+=(fcitx4)
    command -v fcitx5 >/dev/null && installed+=(fcitx5)
    command -v ibus-daemon >/dev/null && installed+=(ibus)
    [ "${#installed[@]}" -eq 1 ] || return 1
    printf '%s\n' "${installed[0]}"
}

main() {
    local framework=auto dry_run=0 format package answer tmp fingerprint name
    local -a admin=()
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --framework) [ "$#" -ge 2 ] || die '--framework 后缺少值'; framework=$2; shift 2;;
            --dry-run) dry_run=1; shift;;
            --help|-h) usage; return;;
            *) usage >&2; die "不支持的参数：$1";;
        esac
    done
    case "$framework" in auto|fcitx4|fcitx5|ibus) ;; *) die '框架必须是 auto、fcitx4、fcitx5 或 ibus';; esac
    [ "$(uname -m)" = x86_64 ] || die '当前安装包只支持 x86_64 / amd64，不能用于 ARM、龙芯、申威或 RISC-V。'
    if command -v apt-get >/dev/null && command -v dpkg >/dev/null; then
        command -v dnf >/dev/null && die '同时检测到 APT 和 DNF，请从下载页手动选择本系统的包格式。'
        [ "$(dpkg --print-architecture)" = amd64 ] || die '当前 DEB 用户空间不是 amd64。'
        format=deb
    elif command -v dnf >/dev/null && command -v rpm >/dev/null; then
        format=rpm
    else
        die '未检测到支持的 APT 或 DNF 环境，请查看 https://maquan.app/guide/linux-domestic-install'
    fi
    if [ "$framework" = auto ]; then
        framework=$(detect_framework) || die '无法唯一确定输入法框架；请用 --framework fcitx4、fcitx5 或 ibus 明确选择。未做任何安装。'
    fi
    [ "$format:$framework" != rpm:fcitx4 ] || die '目前没有 Fcitx4 RPM 包，不会改装 Fcitx5。请反馈系统版本。'
    package=maquan-ime-$framework
    printf '架构：x86_64\n包格式：%s\n选择框架：%s\n安装包：%s\n' "$format" "$framework" "$package"
    printf '%s\n' '只安装选定的码圈前端，不切换或删除系统输入法框架。' \
        '三个码圈前端不可同时安装；换装请先手工卸载旧码圈前端，个人数据保留。' \
        '依赖由系统包管理器检查。系统过旧、只读或安全策略限制时请停止，不要强制安装。'
    [ "$dry_run" -eq 0 ] || { printf '检测结束，未修改系统。\n'; return; }
    read -r -p '是否继续配置码圈软件源并安装？[y/N] ' answer || die '没有收到确认；未安装。'
    case "$answer" in y|Y|yes|YES) ;; *) printf '已取消，未安装。\n'; return;; esac
    for name in curl gpg; do command -v "$name" >/dev/null || die "缺少 $name，请先使用系统包管理器安装。"; done
    if [ "$(id -u)" -ne 0 ]; then
        command -v sudo >/dev/null || die '需要管理员权限，请联系管理员。'
        admin=(sudo)
    fi
    tmp=$(mktemp -d /tmp/maquan-install.XXXXXXXX)
    # Only remove the fresh installer-owned temporary directory.
    case "$tmp" in /tmp/maquan-install.*) ;; *) die '临时目录不符合预期';; esac
    trap "rm -rf -- '$tmp'" EXIT
    curl --proto '=https' --tlsv1.2 -fsSL https://maquan.app/packages/MaQuanIME-Linux-Archive-Key.asc -o "$tmp/key.asc"
    fingerprint=$(gpg --batch --no-options --homedir "$tmp" --show-keys --with-colons "$tmp/key.asc" 2>/dev/null | awk -F: '$1=="fpr" {print $10; exit}')
    [ "$fingerprint" = DDEA0C1D2E89534339719927A6560A4AA577299D ] || die '发行公钥指纹不匹配，拒绝安装。'
    if [ "$format" = deb ]; then
        curl --proto '=https' --tlsv1.2 -fsSL https://maquan.app/packages/maquan-ime.sources -o "$tmp/maquan-ime.sources"
        "${admin[@]}" install -m 0644 "$tmp/key.asc" /usr/share/keyrings/maquan-ime-archive-keyring.asc
        "${admin[@]}" install -m 0644 "$tmp/maquan-ime.sources" /etc/apt/sources.list.d/maquan-ime.sources
        "${admin[@]}" apt-get update
        # Protect vendor frameworks: refuse ANY removals, including a MaQuan swap.
        "${admin[@]}" apt-get --simulate --no-remove install "$package" ||
            die '依赖检查未通过或需要删除现有软件；已停止，不会替换系统输入法框架。请提供完整检查输出。'
        "${admin[@]}" apt-get --no-remove install "$package"
    else
        curl --proto '=https' --tlsv1.2 -fsSL https://maquan.app/packages/maquan-ime.repo -o "$tmp/maquan-ime.repo"
        "${admin[@]}" rpm --import "$tmp/key.asc"
        "${admin[@]}" install -m 0644 "$tmp/maquan-ime.repo" /etc/yum.repos.d/maquan-ime.repo
        # DNF already refuses conflict-driven erasure without --allowerasing.
        # Do not pass allowerasing as a config option: DNF5 rejects it.
        "${admin[@]}" dnf install "$package"
    fi
    printf '%s\n' '安装完成后重启电脑，再在输入法配置中添加“码圈输入法”。' \
        'Fcitx4：fcitx-configtool 或系统输入法设置；Fcitx5：fcitx5-configtool；IBus：ibus-setup。' \
        '设置中心：jdime-settings。详细说明：https://maquan.app/guide/linux-domestic-install'
}

if [[ ${BASH_SOURCE[0]} == "$0" ]]; then main "$@"; fi
