#!/bin/bash
#set -x

WHO=${0##*/}
WHO=${WHO/hotpot/wine}

if [ -f "$HOTPOT_WINE" ]; then
	WINE_PATH=$(dirname "$(dirname ${HOTPOT_WINE})")
fi

if [ "$WINE_PATH" == "" ]; then
    if [ -f "/opt/winux/hotpot9/usr/local/bin/wine" ]; then
        WINE_PATH=/opt/winux/hotpot9/usr/local
    fi
fi

if [ "$WINE_PATH" == "" ]; then
    if [ -f "/opt/winux/hotpot8/usr/local/bin/wine" ]; then
        WINE_PATH=/opt/winux/hotpot8/usr/local
    fi
fi

if [ "$WINE_PATH" == "" ]; then
    if [ -f "/opt/winux/hotpot7/usr/local/bin/wine" ]; then
        WINE_PATH=/opt/winux/hotpot7/usr/local
    fi
fi

if [ "$WINE_PATH" == "" ]; then
    if [ -f "/opt/winux/hotpot6/usr/local/bin/wine" ]; then
        WINE_PATH=/opt/winux/hotpot6/usr/local
    fi
fi

if [ "$WINE_PATH" == "" ]; then
    echo "未安装火锅"
    exit
fi

RUN_TMP_DIR=/
ROOT_FS_RO=/run/hotpot
ARCH="$(uname -m)"
CPU="any"
if LANG=c lscpu | grep -i "aarch64" ; then
	CPU="aarch64";
fi
if LANG=c lscpu | grep -i "loongarch" ; then
	CPU="loongarch";
fi
if LANG=c lscpu | grep -i "Model name" | grep -qi "HUAWEI" ; then
	CPU="huawei";
fi
if cat /proc/cpuinfo | grep Hardware | grep -qi "HUAWEI" ; then
    CPU="huawei";
    ROOT_FS_RO=/opt/exagear/images/kylin-x86_64
fi


# ==== 转译环境：同步 libhotpot-reg.so（ARM 转译器 + 龙芯 LATX）====
if [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "loongarch64" ]; then
    # box64/jiuyi/exagear/latx 引擎安装或更新后需重新同步（首次安装由 postinst 调用）
    # 通过 yuanyanghotpot-sudoer 提权，确保有 /usr 和 /opt 下的写权限
    yuanyanghotpot-sudoer sync-hotpot-lib 2>/dev/null || true
fi

function mk_tmp_rootfs()
{
    RUN_TMP_DIR=$(mktemp -d "/opt/winux/runtime/.hotpot-XXXXXX")
    mkdir ${RUN_TMP_DIR}/{dev,run,sys,proc,etc,usr,root,home,var,media,tmp,data,mnt,srv,boot}
    if [ -L /opt ]; then
        ln -sf $(readlink -f /opt) ${RUN_TMP_DIR}/opt
    else
        mkdir ${RUN_TMP_DIR}/opt
    fi
    ln -sf usr/bin ${RUN_TMP_DIR}/bin
    ln -sf usr/sbin ${RUN_TMP_DIR}/sbin
    ln -sf usr/lib ${RUN_TMP_DIR}/lib
    ln -sf usr/lib32 ${RUN_TMP_DIR}/lib32
    ln -sf usr/lib64 ${RUN_TMP_DIR}/lib64
    ln -sf usr/libx32 ${RUN_TMP_DIR}/libx32
}

OS_VERSION="$(lsb_release -ir | awk '{print $NF}')"

function generate_bwrap_params()
{
    #mk_tmp_rootfs

    # SRC: 宿主机真实 .so（hotpot-register 4.2.1 新目录）
    # DST: wineserver 内 do_check_reg 硬编码的旧路径，需桥接才能被 wine 进程加载
    case "${ARCH}" in
        aarch64)
            HOTPOT_REG_LIB_SRC="/opt/winux/hotpot-register/libhotpot-reg/aarch64/libhotpot-reg.so"
            HOTPOT_REG_LIB_DST="/usr/lib/aarch64-linux-gnu/libhotpot-reg.so"
            ;;
        i386|i686)
            HOTPOT_REG_LIB_SRC="/opt/winux/hotpot-register/libhotpot-reg/i386/libhotpot-reg.so"
            HOTPOT_REG_LIB_DST="/usr/lib/i386-linux-gnu/libhotpot-reg.so"
            ;;
        *)
            HOTPOT_REG_LIB_SRC="/opt/winux/hotpot-register/libhotpot-reg/x86_64/libhotpot-reg.so"
            HOTPOT_REG_LIB_DST="/usr/lib/x86_64-linux-gnu/libhotpot-reg.so"
            ;;
    esac

    BWRAP_ARGS=(
        --bind ${RUN_TMP_DIR}  /
        --ro-bind ${ROOT_FS_RO}/etc /etc
        --ro-bind ${ROOT_FS_RO}/usr /usr
        --ro-bind ${ROOT_FS_RO}/var /var
        --ro-bind /etc/passwd /etc/passwd
        --ro-bind /etc/group  /etc/group
        --ro-bind /etc/shadow  /etc/shadow
        --ro-bind /etc/resolv.conf /etc/resolv.conf
        --ro-bind /etc/localtime   /etc/localtime
        --ro-bind /etc/nsswitch.conf /etc/nsswitch.conf
        --ro-bind /etc/hosts /etc/hosts
        --ro-bind /usr/bin/yuanyanghotpot-sudoer /usr/bin/yuanyanghotpot-sudoer
        --ro-bind /usr/bin/yuanyanghotpot /usr/bin/yuanyanghotpot
        --ro-bind /var/cache/fontconfig/ /var/cache/fontconfig/
        --ro-bind /usr/share/fonts /usr/share/fonts
        --proc /proc
        --dev-bind /dev /dev
        --dev-bind /dev/pts /dev/pts
        --bind /dev/shm /dev/shm
        --ro-bind /sys /sys
        --ro-bind /run /run
        --bind /run/user/"$(id -u)" /run/user/"$(id -u)"
        --bind /run/dbus /run/dbus
        --setenv XDG_RUNTIME_DIR "/run/user/`id -u`"
        --setenv DISPLAY "${DISPLAY:-:0}"
        --setenv XAUTHORITY "${XAUTHORITY:-${HOME}/.Xauthority}"
        --setenv DBUS_SESSION_BUS_ADDRESS "unix:path=/run/user/$(id -u)/bus"
    )
    
    # 运行时缓存和 schema，仅源文件存在时才绑定
    if [ -f "/opt/winux/runtime/etc/ld.so.cache" ]; then
        BWRAP_ARGS+=(--ro-bind /opt/winux/runtime/etc/ld.so.cache /etc/ld.so.cache)
    fi
    if [ -d /usr/share/fdhotpot ] &&  [ -d /run/hotpot/usr/share/fdhotpot ]; then
        BWRAP_ARGS+=(--ro-bind /usr/share/fdhotpot /usr/share/fdhotpot)
    fi

    # mk_tmp_rootfs 未启用，RUN_TMP_DIR 始终为 /，以下 /opt 绑定分支暂注释
    # if [ ${RUN_TMP_DIR} != "/" ]; then
    #     if [ -L /opt ]; then
    #         OPT_REAL_PATH=$(readlink -f /opt)
    #         BWRAP_ARGS+=(--ro-bind "${OPT_REAL_PATH}" "${OPT_REAL_PATH}")
    #     else
    #         BWRAP_ARGS+=(--ro-bind /opt /opt)
    #     fi
    # fi
}

# wine11+(new WoW64) 不再有独立的 wine64 二进制, 自动回退到 wine
if [ ! -x "${WINE_PATH}/bin/${WHO}" ] && [ "${WHO}" = "wine64" ] && [ -x "${WINE_PATH}/bin/wine" ]; then
    WHO="wine"
fi

# ==== winetricks 运行环境 ====
# x86 通过 bwrap 沙箱提供 32 位运行时（解决宿主缺 /lib/ld-linux.so.2）；
# ARM 转译环境（box64/exagear）自带完整运行时，直接运行。
# loongarch64（LATX）：bwrap 沙箱内 /usr 被替换为 x86 wine runtime，/bin/sh 会解析到 x86 dash 无法执行，
# 因此也直接运行（宿主 sh 原生可执行，wine 由 binfmt LATX 转译）。
if [ "${WHO}" = "winetricks" ]; then
    export WINE="${WINE:-${WINE_PATH}/bin/wine}"
    if [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "loongarch64" ]; then
        exec /opt/winux/tools/appmanager/winetricks "$@"
    elif mountpoint -q /run/hotpot && [ -z "${NOCON+x}" ]; then
        generate_bwrap_params
        # 沙箱内 /usr 是只读 squashfs，/opt/winux/tools/appmanager 是 root 所有，
        # 普通用户 bwrap 都无法在其中创建挂载点。用 mktemp 临时目录（普通用户可写）承载工具。
        # cabextract/unzip 是字体/dll 解压的核心工具（其余 7z/unrar 走 winetricks 的 Windows 7-Zip 回退）。
        tool_dir="$(mktemp -d /tmp/winetricks-tools.XXXXXX)"
        for tool in cabextract unzip; do
            tp="$(command -v "$tool" 2>/dev/null)"
            [ -n "$tp" ] && BWRAP_ARGS+=(--ro-bind "$tp" "${tool_dir}/${tool}")
        done
        # cabextract 依赖 libmspack（wine runtime 不含），一并 bind 并通过 LD_LIBRARY_PATH 暴露
        mspack_path="$(ldd "$(command -v cabextract 2>/dev/null)" 2>/dev/null | awk '/libmspack/ {print $3}')"
        if [ -n "$mspack_path" ] && [ -e "$mspack_path" ]; then
            BWRAP_ARGS+=(--ro-bind "$mspack_path" "${tool_dir}/libmspack.so.0")
        fi
        BWRAP_ARGS+=(--setenv PATH "${tool_dir}:${PATH}")
        BWRAP_ARGS+=(--setenv LD_LIBRARY_PATH "${tool_dir}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}")
        exec bwrap "${BWRAP_ARGS[@]}" -- /opt/winux/tools/appmanager/winetricks "$@"
    else
        exec /opt/winux/tools/appmanager/winetricks "$@"
    fi
    exit $?
fi

# ==== ARM box64 转译环境 ====
# wine-link 本身是 ARM 原生 bash，不会被 box64 翻译执行。
# 检测到 box64 模式时，直接 exec box64 + 原生 wine ELF，跳过 BWRAP。
if [ "$HOTPOT_TRANSLATION_ENGINE" = "box64" ] && [ "$ARCH" = "aarch64" ]; then
    BOX64_BIN_PATH="/opt/winux/nfs-box64/usr/bin/box64"
    if [ "${HOTPOT_TRANSLATION_BIN}x" != "x" ] && [ -x ${HOTPOT_TRANSLATION_BIN} ]; then
        BOX64_BIN="${HOTPOT_TRANSLATION_BIN}"
    else
        BOX64_BIN="${BOX64_BIN_PATH}"
    fi
    WINE_PRELOADER="${WINE_PATH}/lib/wine/x86_64-unix/wine-preloader"
    # 如果应用不是wow64编译的wine-preloader在usr/local/bin/下
    if [ ! -f "$WINE_PRELOADER" ]; then
        WINE_PRELOADER="${WINE_PATH}/bin/wine-preloader"
    fi
    if [ -f "$WINE_PRELOADER" ] && [ -f "$BOX64_BIN" ]; then
        exec "$BOX64_BIN" "$WINE_PRELOADER" "${WINE_PATH}/bin/${WHO}" "$@"
        exit 0;
    fi
fi

# main 
if [ ${CPU} = "huawei" ]; then
    /usr/bin/exagear -- "${WINE_PATH}/bin/${WHO}" "$@"
elif [ ${ARCH} = "aarch64" ]; then
    /opt/phybin/bin/jiuyi "${WINE_PATH}/bin/${WHO}" "$@"
elif [ ${ARCH} = "loongarch64" ]; then
    # 龙芯：x86 wine 由 LATX 翻译执行，guest 库由 hotpot-rt 挂载到 /run/hotpot
    # latx-wrapper 默认 LAT_LD_PREFIX=/run/wine（麒麟 wine-runtime），方案二需覆盖为 /run/hotpot
    export LAT_LD_PREFIX="${LAT_LD_PREFIX:-/run/hotpot}"
    "${WINE_PATH}/bin/${WHO}" "$@"
elif mountpoint -q /run/hotpot && [[ -z ${NOCON+x} ]]; then
    generate_bwrap_params
    if [ -z ${B_DEBUG+x} ]; then
        exec bwrap "${BWRAP_ARGS[@]}" -- "${WINE_PATH}/bin/${WHO}" "$@"
    else
        echo "enter to bwrap ns."
	BWRAP_ARGS+=(--setenv PS1 "\[\e[01;31m\][bwrap] \\[\e[02;32m\]\u@\h:\[\033[01;34m\]\w\[\033[00m\]\$ ")
        exec bwrap "${BWRAP_ARGS[@]}" -- "/usr/bin/bash" --norc
    fi
else
 "${WINE_PATH}/bin/${WHO}" "$@"
fi
