#!/bin/bash
# =============================================================================
# amber-pm-desktop-fix —— APM 桌面集成
#
# 2.0.0 起 APM 包直接安装在宿主 /var/lib/apm/<包名>/，不再有管理环境。
# 本脚本把每个包 entries/ 下的桌面文件与图标链接到桌面环境能找到的目录：
#   * 麒麟系统: /usr/share/{applications,icons}
#   * KDE:      /usr/local/share/applications/apm
#   * 其他:     /usr/local/share/applications
# 同时清理旧版本（管理环境路径）留下的失效链接，并修复 2.0.2 版
# amber-pm-convert 写坏的 Icon 绝对路径。
# =============================================================================

APM_STATE_DIR="${APM_STATE_DIR:-/var/lib/apm}"
APM_STATE_DIR="${APM_STATE_DIR%/}"

is_kde_plasma() {
    if [ -f /usr/share/xsessions/plasma.desktop ] ||
        [ -f /usr/share/xsessions/plasma-xorg.desktop ] ||
        [ -f /usr/share/xsessions/plasma-wayland.desktop ] ||
        [ -f /usr/local/share/xsessions/plasma.desktop ] ||
        [ -f /usr/local/share/xsessions/plasma-xorg.desktop ] ||
        [ -f /usr/local/share/xsessions/plasma-wayland.desktop ] ||
        command -v startplasma-x11 >/dev/null 2>&1 ||
        command -v startplasma-wayland >/dev/null 2>&1 ||
        command -v plasmashell >/dev/null 2>&1; then
        return 0
    fi
    return 1
}

if grep -q "Kylin" /etc/os-release 2>/dev/null; then
    APP_TARGET_DIR="${APP_TARGET_DIR:-/usr/share/applications}"
    ICON_TARGET_DIR="${ICON_TARGET_DIR:-/usr/share/icons}"
elif is_kde_plasma; then
    APP_TARGET_DIR="${APP_TARGET_DIR:-/usr/local/share/applications/apm}"
    ICON_TARGET_DIR="${ICON_TARGET_DIR:-/usr/local/share/icons}"
else
    APP_TARGET_DIR="${APP_TARGET_DIR:-/usr/local/share/applications}"
    ICON_TARGET_DIR="${ICON_TARGET_DIR:-/usr/local/share/icons}"
fi

ensure_dir() {
    local dir="$1"
    [ -n "$dir" ] || return 1
    [ -d "$dir" ] || mkdir -p "$dir"
}

# 递归地把图标目录里的文件链接到目标目录
_link_icons() { # 源目录 目标目录
    local src="$1" dst="$2" f rel target
    [ -d "$src" ] || return 0
    while IFS= read -r -d '' f; do
        rel="${f#"$src"/}"
        target="$dst/$rel"
        ensure_dir "$(dirname -- "$target")" || continue
        ln -sfn "$(realpath -- "$f")" "$target" 2>/dev/null || true
    done < <(find "$src" -type f -print0 2>/dev/null)
}

_link_applications() { # 源目录 目标目录
    local src="$1" dst="$2" f
    [ -d "$src" ] || return 0
    while IFS= read -r -d '' f; do
        ln -sfn "$(realpath -- "$f")" "$dst/$(basename -- "$f")" 2>/dev/null || true
    done < <(find "$src" -maxdepth 1 -type f -name '*.desktop' -print0 2>/dev/null)
}

# 清理指向旧管理环境的失效链接（只动 /var/lib/apm 相关的）
_cleanup_stale_links() {
    local f target
    for f in "$APP_TARGET_DIR"/*.desktop; do
        [ -L "$f" ] || continue
        target="$(readlink -- "$f" 2>/dev/null)" || continue
        case "$target" in
            *ace-env* | *"/var/lib/apm/"*)
                if [ ! -e "$target" ]; then
                    rm -f -- "$f"
                fi
                ;;
        esac
    done
}

ensure_dir "$APP_TARGET_DIR"
ensure_dir "$ICON_TARGET_DIR"

# APM's host integration data directory. XDG_DATA_DIRS points here via
# /etc/profile.d/apm.sh, /etc/X11/Xsession.d/20apm and the systemd user
# environment generator, so desktop environments can find APM applications.
APM_XDG_DATA_DIR="$APM_STATE_DIR/apm/files/ace-env/amber-ce-tools/data-dir"

# 旧版 APM 可能在 /usr/local/share/icons 里留下
# hicolor -> .../data-dir/icons//hicolor 这类链接。
# 新版 data-dir/icons 指向 /usr/local/share/icons 后会形成符号链接环，
# 这里在建立新链接前清理这种旧 APM 自引用链接。
_cleanup_apm_data_dir_loops() {
    local f target
    if [ -L "$APM_XDG_DATA_DIR/applications" ] || [ ! -d "$APM_XDG_DATA_DIR/applications" ]; then
        for f in "$APP_TARGET_DIR"/*; do
            [ -L "$f" ] || continue
            target="$(readlink -- "$f" 2>/dev/null || true)"
            case "$target" in
                *"/amber-ce-tools/data-dir/applications"* | *"$APM_XDG_DATA_DIR/applications"*)
                    rm -f -- "$f" 2>/dev/null || true
                    ;;
            esac
        done
    fi
    if [ -L "$APM_XDG_DATA_DIR/icons" ] || [ ! -d "$APM_XDG_DATA_DIR/icons" ]; then
        for f in "$ICON_TARGET_DIR"/*; do
            [ -L "$f" ] || continue
            target="$(readlink -- "$f" 2>/dev/null || true)"
            case "$target" in
                *"/amber-ce-tools/data-dir/icons"* | *"$APM_XDG_DATA_DIR/icons"*)
                    rm -f -- "$f" 2>/dev/null || true
                    ;;
            esac
        done
    fi
}

_link_apm_data_dir() { # name target
    local name="$1" target="$2"
    local link="$APM_XDG_DATA_DIR/$name"
    [ -e "$target" ] || return 0
    if [ -L "$link" ] || [ ! -e "$link" ]; then
        ln -sfn "$target" "$link" 2>/dev/null || true
    fi
}

if ensure_dir "$APM_XDG_DATA_DIR"; then
    _cleanup_apm_data_dir_loops
    _link_apm_data_dir applications "$APP_TARGET_DIR"
    _link_apm_data_dir icons "$ICON_TARGET_DIR"
    for _shared_dir in mime pixmaps templates; do
        _link_apm_data_dir "$_shared_dir" "/usr/share/$_shared_dir"
    done
fi

# 2.0.2 的 amber-pm-convert 把 "Icon=/" 替换成了 ".../files/core"（少写一个 /），
# 导致桌面文件里出现宿主上并不存在的路径：
#   Icon=/var/lib/apm/<包名>/files/coreusr/share/icons/...
# 这里统一修成 .../files/core/usr/share/icons/...，让已经安装的包在升级 APM
# 或重新安装后自动恢复图标；顺带把历史遗留的 files/core// 归一成单斜杠。
_repair_desktop_icon() { # desktop 文件
    local f="$1"
    # 只匹配真正有问题的两种写法，正确路径（files/core/...）不做无谓改写
    grep -qE '^Icon=/var/lib/apm/[^/]+/files/core([^/]|//)' "$f" 2>/dev/null || return 0
    sed -i -E \
        -e 's|^(Icon=/var/lib/apm/[^/]+/files/core)([^/])|\1/\2|' \
        -e 's|^(Icon=/var/lib/apm/[^/]+/files/core)/+|\1/|' \
        "$f" 2>/dev/null || true
}

_repair_icon_paths() {
    local f d
    # 包内的桌面文件：只用 -type f 过滤，避免 sed -i 把符号链接替换成普通文件
    while IFS= read -r -d '' f; do
        _repair_desktop_icon "$f"
    done < <(find "$APM_STATE_DIR" -path '*/entries/applications/*.desktop' -type f -print0 2>/dev/null)
    # 桌面环境目录里的真实副本（部分发行版会复制而不是链接）
    for d in "$APP_TARGET_DIR" /usr/share/applications /usr/local/share/applications; do
        [ -d "$d" ] || continue
        while IFS= read -r -d '' f; do
            _repair_desktop_icon "$f"
        done < <(find "$d" -maxdepth 1 -type f -name '*.desktop' -print0 2>/dev/null)
    done
    return 0
}

_repair_icon_paths

for pkgdir in "$APM_STATE_DIR"/*/; do
    [ -d "$pkgdir" ] || continue
    pkg="$(basename -- "$pkgdir")"
    [ "$pkg" = "apm" ] && continue
    [ -d "$pkgdir/entries" ] || continue
    _link_applications "$pkgdir/entries/applications" "$APP_TARGET_DIR"
    _link_icons "$pkgdir/entries/icons" "$ICON_TARGET_DIR"
done

_cleanup_stale_links

if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "$APP_TARGET_DIR" >/dev/null 2>&1 &
fi

exit 0
