#!/bin/bash

rootdir=$(dirname $0)
rootdir=$(realpath $rootdir)

if [ ! -f "$rootdir/bin/wine" ];then
    winename=$(basename $0)
    rootdir="/opt/$winename"

    if [ ! -f "$rootdir/bin/wine" ];then
        echo "not found wine"
        exit
    fi
fi

wine=$rootdir/bin/wine

if test -z "$WINEPREFIX"; then
    if test "$wine" = "$wine64"; then
        wineprefix=$HOME/.wine64
    else
        wineprefix=$HOME/.wine
    fi
else
    wineprefix=$WINEPREFIX
fi

if test -z "$WINELOADER"; then
    wineloader=$wine
else
    wineloader=$WINELOADER
fi

if test -z "$WINEDEBUG"; then
    winedebug=-all
else
    winedebug=$WINEDEBUG
fi

runtime_path=/opt/deepinwine/runtime-i386

export LD_LIBRARY_PATH="$rootdir/lib:$rootdir/lib64:$LD_LIBRARY_PATH"
export WINEDLLPATH="$rootdir/lib:$rootdir/lib64"

# 32位wine需要指定32位runtime的路径
if [ -f "$runtime_path/init_runtime.sh" ];then
    source "$runtime_path/init_runtime.sh"

    PE_FILE="$1"
    if [[ "$1" == *".exe" ]]; then
        PE_FILE=${PE_FILE//\\/\/}
        drive=${PE_FILE:0:2}
        if [[ ${drive} == "c:"* || ${drive} == "C:"* ]]; then
            PE_FILE=${wineprefix}/drive_c${PE_FILE:2}
        fi
    fi

    init_runtime
    if [ -f "$PE_FILE" ];then
        #only 32 bit application need config this envs
        if file "$PE_FILE" | grep -q -e "PE32 "; then
            init_32bit_config
        fi
    fi
    export WINELOADERNOEXEC=1
    winepreloader=$rootdir/bin/wine-preloader
    WINEPREFIX=$wineprefix WINELOADER=$wineloader WINEDEBUG=$winedebug $winepreloader $wine "$@"
else
    WINEPREFIX=$wineprefix WINELOADER=$wineloader WINEDEBUG=$winedebug $wine "$@"
fi
