#!/bin/bash

SELF=$(readlink -f "$0")
BOTTLE="%BOTTLE%"
export WINEPREFIX="$HOME/.kylinwine/${BOTTLE}"
export WINEARCH="%ARCH%"
export PATH=$(dirname $SELF):$PATH
disclaimer="/opt/kylin-wine/app/${BOTTLE}/Disclaimers-${BOTTLE}.txt"
AUTH="%AUTH%"
%ENVIRONMENT%
RUN_ARCH="$(uname -m)"
kylinwine_tips="/opt/kylin-wine/inst-translation/kylinwine_tips.${RUN_ARCH}"
WINE_BIN="%WINEBIN%"

init_bottle()
{
    if [ -x "$kylinwine_tips" ]; then
        {kylinwine_tips} auth $disclaimer
        if [ "$?" != "0" ]; then exit 1; fi
    else
        title="${BOTTLE} (win32)"
        problem=$(cat $disclaimer)
        cancel="拒绝"
        ok="接受"
        zenity --question \
                --title="${title}" \
                --text="${problem}" \
                --cancel-label="${cancel}" \
                --ok-label="${ok}" \
                --width=500 \
                --height=200 \
                --window-icon="info" \
                --icon-name="info"

        if [ "$?" != "0" ]; then exit 1; fi
    fi


    wine-env-toolkit "init"
	echo $AUTH > "${WINEPREFIX}/.disclaimer"
}

wine-env-toolkit "check"
if [ "$?" != "1" ]; then
    IS_DISCLAIMER=$(cat "${WINEPREFIX}/.disclaimer")
    if [ "$AUTH" != "$IS_DISCLAIMER" ]; then
        init_bottle
    fi
else
		init_bottle
fi

get_emulator()
{
    if [ "$RUN_ARCH" = "x86_64" ]; then
        echo "eval "
    elif egrep -q "CPU implementer[[:space:]]*:[[:space:]]*0x70" /proc/cpuinfo; then
        echo "phybin --"
    elif grep -q "CPU implementer[[:space:]]*:[[:space:]]*0x48" /proc/cpuinfo; then
        echo "exagear --"
    else
        echo "eval "
    fi
}

show_tips()
{
    if [ -x "$kylinwine_tips" ]; then
        $kylinwine_tips monitor app "%EXECNAME%" 60 "正在启动\"%EXECNAME%\"" > /dev/null &
    fi
}

file "${WINE_BIN%/*}/wine" | grep -q "aarch64" && IS_ARM64EC=1 || IS_ARM64EC=0

%ISRUNWINE%show_tips
IFS=" "
%ISRUNWINE%read EMULATOR params <<< $(get_emulator)
%ISRUNWINE%cmd="\"$WINE_BIN\" start /d \"%EXECPATH%\" \"%EXECNAME%\" %PARAM%" 
%ISRUNWINE%if [ "$IS_ARM64EC" = "0" ]; then
%ISRUNWINE%    $EMULATOR $params "$cmd"
%ISRUNWINE%else
%ISRUNWINE%    export EMULATOR
%ISRUNWINE%    eval "$cmd"
%ISRUNWINE%fi
