#!/bin/bash

name=${0##*/}
bindir=/usr/lib/$name

wine32=/opt/$name/bin/wine
wine64=/opt/$name/bin/wine64

if test -x $wine32 -a "$WINEARCH" != "win64"; then
    wine=$wine32
elif test -x $wine64; then
    wine=$wine64
    if [ "$(dpkg --print-architecture)" = "amd64" -a "$(dpkg --print-foreign-architectures | grep -cx "i386")" -ne 1 ]; then
        echo "it looks like multiarch needs to be enabled.  as root, please"
        echo "execute \"dpkg --add-architecture i386 && apt-get update &&"
        echo "apt-get install $(echo $name | sed s/wine/wine32/)\""
    fi
else
    echo "error: unable to find wine executable.  this shouldn't happen."
    exit 1
fi

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="/opt/$name/lib:/opt/$name/lib64:$LD_LIBRARY_PATH"
export WINEDLLPATH=/opt/$name/lib:/opt/$name/lib64

# 32位wine需要指定32位runtime的路径
if [ -f "$runtime_path/init_runtime.sh" -a "$wine" = "$wine32" ];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=/opt/$name/bin/wine-preloader
    WINEPREFIX=$wineprefix WINELOADER=$wineloader WINEDEBUG=$winedebug $winepreloader $wine "$@"
else
    WINEPREFIX=$wineprefix WINELOADER=$wineloader WINEDEBUG=$winedebug $wine "$@"
fi
