#!/bin/bash

# ===== Log Functions with Colors =====
log.warn() { echo -e "[\e[33mWARN\e[0m]:  \e[1m$*\e[0m"; }
log.error() { echo -e "[\e[31mERROR\e[0m]: \e[1m$*\e[0m"; }
log.info() { echo -e "[\e[96mINFO\e[0m]:  \e[1m$*\e[0m"; }
log.debug() { echo -e "[\e[32mDEBUG\e[0m]: \e[1m$*\e[0m"; }

# Zenity wrapper function
gui_dialog() {
    if command -v garma &>/dev/null; then
        garma "$@"
    else
        zenity "$@"
    fi
}

# Check if no arguments were passed
if [[ $# -eq 0 ]]; then
    gui_dialog --info --text="使用方法：\nUsage:\n\nspark-wine9 <application.exe>\n\n请提供要运行的 Windows 应用程序。\nPlease provide the Windows application to run."
    exit 1
fi

# Check if spark-wine9 is installed
if [[ ! -e  "/usr/bin/spark-wine9" ]]; then
    gui_dialog --question --text="您尚未安装 spark-wine9 ，是否安装以运行 Windows 应用？\nYou haven't installed spark-wine9 yet. Would you like to install it to run Windows applications?"
    if [[ $? -ne 0 ]]; then
        log.error "User refused to install. Exiting."
        exit 1
    fi
    

# Install spark-wine with progress indicator
pkexec bash -c "aptss update && aptss install spark-wine9 spark-wine9-mono -y" | gui_dialog --progress --pulsate --auto-close --no-cancel --text="正在安装，请保持网络畅通，耐心等待\nInstalling, please keep network connection and wait patiently"
INSTALL_STATUS=${PIPESTATUS[0]}

# Check the installation status correctly
if [[ $INSTALL_STATUS -ne 0 ]]; then
    gui_dialog --error --text="安装出错，请手动执行以下指令查看错误并反馈：\nError occurred during installation. Please execute the command below to view the error log:\n\nsudo aptss install spark-wine9 spark-wine9-mono -y"
    exit 1
fi


fi

# Run spark-wine with WINEPREFIX
export WINEPREFIX="${WINEPREFIX:=$HOME/.deepinwine/spark-wine-custom}"  
export APPRUN_CMD="/usr/bin/spark-wine9"
export SHELL_DIR="/opt/spark-dwine-helper"

if [[ "$WINEPREFIX" != $HOME/.deepinwine/spark-wine-custom ]];then
${APPRUN_CMD} "$@"
exit
fi



(
mkdir -p ${WINEPREFIX}
${SHELL_DIR}/spark-dwine-helper/scale-set-helper/set-wine-scale.sh ${WINEPREFIX} &
# ${APPRUN_CMD} reg add 'HKEY_CURRENT_USER\Software\Wine\DllOverrides' /v winemenubuilder.exe /f & 
wait
) | gui_dialog --progress --pulsate --auto-close --no-cancel --text="正在准备应用...\nPreparing Windows APP..."

${APPRUN_CMD} "$@"
/opt/spark-dwine-helper/spark-dwine-helper/spark-wine-desktop-auto-cleanner
