#!/usr/bin/env bash
# Author: Castro-Fidel (PortWINE-Linux.ru)
########################################################################
pw_ping_test () {
    ping -w3 -c1 github.com &> /dev/null
    [ "$?" == "0" ] && return 0 || return 1
}

print_error () {
    echo "ERROR: $@"
}
export -f print_error

print_info () {
    echo "INFO: $@"
}
export -f print_info


print_var () {
    for vp in $@ ; do echo "${vp}=${!vp}" ; done
}
export -f print_var

try_copy_file () {
    if [ ! -f "$1" ] ; then	print_info "file $1 not found for copy" && return 1
    elif [ -z "$2" ] ; then	print_error "no way to copy file $1" && return 1
    else
        cp -f "$1" "$2"
        if [ "$?" != 0 ]
        then print_error "failed to copy file $1 to $2" || return 1
        else return 0
        fi
    fi
}
export -f try_copy_file

try_copy_dir () {
    if [ ! -d "$1" ] ; then	print_info "directory $1 not found for copy"
    elif [ -z "$2" ] ; then	print_error "no way to copy directory $1"
    else
        cp -fr "$1" "$2"
        [ "$?" != 0 ] && print_error "failed to copy directory $1 to $2" || return 0
    fi
    return 1
}
export -f try_copy_dir

try_remove_file () {
    if [ -f "$1" ] ; then
        rm -f "$1"
        [ "$?" == 0 ] && return 0 || return 1
    fi
}
export -f try_remove_file

try_remove_dir () {
    if [ -d "$1" ] ; then
        rm -fr "$1"
        [ "$?" == 0 ] && return 0 || return 1
    fi
}
export -f try_remove_dir

try_force_link_file () {
    if [ ! -f "$1" ] ; then	print_info "file $1 not found for link"
    elif [ -z "$2" ] ; then	print_error "no way to link file $1"
    else
        ln -sf "$1" "$2"
        [ "$?" != 0 ] && print_error "failed to link file $1 to $2" || return 0
    fi
    return 1
}
export -f try_force_link_file

check_symlink () {
    CHK_SYMLINK_FILE="`file "$1"`"
    if [[ ! -z "`echo "$CHK_SYMLINK_FILE" | grep -v "broken" | grep "symbolic link to" | awk '{print $1}'`" ]] ; then
        return 0
    elif [[ ! -z "`echo "$CHK_SYMLINK_FILE" | grep "broken symbolic link to" | awk '{print $1}'`" ]] ; then
        print_error "remove broken symlink: $CHK_SYMLINK_FILE"
        rm -fr "$CHK_SYMLINK_FILE"
        return 1
    else
        return 1
    fi
}
export -f check_symlink

try_force_link_dir () {
    if [ ! -d "$1" ] ; then	print_info "directory $1 not found for link"
    elif [ -z "$2" ] ; then	print_error "no way to link directory $1"
    else
        ln -sf "$1" "$2"
        [ "$?" != 0 ] && print_error "failed to link directory $1 to $2" || return 0
    fi
    return 1
}
export -f try_force_link_dir

check_process () {
    [ ! -n "`ps cax | grep "$1" | awk '{print $1}'`" ] && return 0 || return 1 
}
export -f check_process

try_download () {
    set -o pipefail
    wget -O "$2" --read-timeout 300 --retry-connrefused --timeout 15 --tries 3 \
    --user-agent="Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" "$1" 2>&1 | \
    tr '\r' '\n' | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9,.]\+.\) \(.*\)/\1\n#Downloading at \1\/, \2\/s, ETA \3/; s/^20[0-9][0-9].*/#Done./' | \
    zenity --progress --percentage=0 --title="Download $(basename $1)" --text=Starting... --auto-close --width=500 --height=90
    if [ "${PIPESTATUS[0]}" != 0 ] ; then
        print_error "failed to download $1. Skipping."
        try_remove_file "$2"
        return 1 
    else
        return 0
    fi
    try_remove_file "${PORT_WINE_TMP_PATH}/download_log"
}

try_download_to_path () {
    set -o pipefail
    wget --directory-prefix="$2" --read-timeout 300 --retry-connrefused --timeout 15 --tries 3 \
    --user-agent="Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" "$1" 2>&1 | \
    tr '\r' '\n' | sed -u 's/.* \([0-9]\+%\)\ \+\([0-9,.]\+.\) \(.*\)/\1\n#Downloading at \1\/, \2\/s, ETA \3/; s/^20[0-9][0-9].*/#Done./' | \
    zenity --progress --percentage=0 --title="Download $(basename $1)" --text=Starting... --auto-close --width=500 --height=90
    if [ "${PIPESTATUS[0]}" != 0 ] ; then
        print_error "failed to download $1. Skipping."
        return 1 
    else 
        return 0
    fi
}

try_download_silent () {
    wget -O "$2" --read-timeout 300 --retry-connrefused --timeout 15 --tries 3 \
    --user-agent="Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" "$1"
    if [ "${PIPESTATUS[0]}" != 0 ] ; then
        print_error "failed to download $1. Skipping."
        try_remove_file "$2"
        return 1 
    else 
        return 0
    fi
}

create_new_dir () {
    if [ ! -d "$1" ] ; then
        mkdir -p "$1"
    fi
    return 0
}

var_winedlloverride_update () {
    if [ ! -z "${WINEDLLOVERRIDES}" ]
    then export WINEDLLOVERRIDES="${1};${WINEDLLOVERRIDES}"
    else export WINEDLLOVERRIDES="${1}"
    fi
    return 0
}

var_vkd3d_config_update () {
    if [ ! -z "${VKD3D_CONFIG}" ]
    then export VKD3D_CONFIG="${1};${VKD3D_CONFIG}"
    else export VKD3D_CONFIG="${1}"
    fi
    return 0
}

var_radv_perftest_config_update () {
    if [ ! -z "${RADV_PERFTEST}" ]
    then export RADV_PERFTEST="${1};${RADV_PERFTEST}"
    else export RADV_PERFTEST="${1}"
    fi
    return 0
}

var_vk_istance_layers_config_update () {
    if [ ! -z "${PW_VK_INSTANCE_LAYERS}" ]
    then export PW_VK_INSTANCE_LAYERS="${1}:${PW_VK_INSTANCE_LAYERS}"
    else export PW_VK_INSTANCE_LAYERS="${1}"
    fi
    return 0
}

unpack_tar_xz () {
    set -o pipefail
    tar -Jxvf "$1" -C "$2" | sszen
    [ "${PIPESTATUS[0]}" != 0 ] && print_error "File $1 unpacking error." && return 1 || return 0
}

unpack_tar_gz () {
    set -o pipefail
    tar -xzvf "$1" -C "$2" | sszen
    [ "${PIPESTATUS[0]}" != 0 ] && print_error "File $1 unpacking error." && return 1 || return 0
}

unpack_tar () {
    set -o pipefail
    tar -xvf "$1" -C "$2" | sszen
    [ "${PIPESTATUS[0]}" != 0 ] && print_error "File $1 unpacking error." && return 1 || return 0
}

pw_clear_pfx () {
    try_remove_file "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/system.reg"
    try_remove_file "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/user.reg"
    try_remove_file "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/userdef.reg"
    try_remove_file "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
    try_remove_file "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/.update-timestamp"
    try_remove_file "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/.windows-serial"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/windows/"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/ProgramData/Setup"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/ProgramData/Windows"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/ProgramData/WindowsTask"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/ProgramData/Package Cache"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/Public/Local Settings/Application Data/Microsoft"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/Public/Local Settings/Application Data/Temp"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/Public/Local Settings/Temporary Internet Files"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/Public/Application Data/Microsoft"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/Public/Application Data/wine_gecko"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/Public/Temp"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/steamuser/Local Settings/Application Data/Microsoft"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/steamuser/Local Settings/Application Data/Temp"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/steamuser/Local Settings/Temporary Internet Files"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/steamuser/Application Data/Microsoft"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/steamuser/Application Data/wine_gecko"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/users/steamuser/Temp"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/Program Files/Internet Explorer"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/Program Files/Windows Media Player"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/Program Files/Windows NT"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/Program Files/Common Files"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/Program Files (x86)/Internet Explorer"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/Program Files (x86)/Common Files"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/Program Files (x86)/Windows Media Player"
    try_remove_dir "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/Program Files (x86)/Windows NT"
    try_remove_dir "${PORT_WINE_TMP_PATH}/mesa_shader_cache"
    rm -f "${PORT_WINE_TMP_PATH}"/*.bin
    rm -f "${PORT_WINE_TMP_PATH}"/*.foz
    return 0
}

check_user_conf () {
    if [ ! -f "${USER_CONF}" ]; then
        echo "#!/usr/bin/env bash" > "${USER_CONF}"
        echo "# User overides db and var settings..." >> "${USER_CONF}"
        chmod u+x "${USER_CONF}"
    fi
    return 0
}

init_wine_ver () {
    if [[ -z `ls "${PORT_WINE_PATH}/data/dist/" | grep "${PW_WINE_USE}"` ]] ; then
        if [[ ! -z `echo "${PW_WINE_USE}" | grep "PROTON_STEAM"` ]] ; then
            export PW_WINE_USE=PROTON_STEAM
        else
            export PW_WINE_USE=PROTON_GE
        fi
    fi
    if [[ ! -z `echo "${PW_WINE_USE}" | grep "^PROTON_STEAM$"` ]] 
    then export PW_WINE_USE="${PW_PROTON_STEAM_VER}"
    elif [[ ! -z `echo "${PW_WINE_USE}" | grep "^PROTON_GE$"` ]]
    then export PW_WINE_USE="${PW_PROTON_GE_VER}"
    fi
    [ ! -z "${PW_WINE_VER}" ] && export PW_WINE_USE=`echo "${PW_WINE_VER}" | tr [[:lower:]] [[:upper:]]`
    [ ! -z "${PW_WINE_USE}" ] && export PW_WINE_USE=`echo "${PW_WINE_USE}" | tr [[:lower:]] [[:upper:]]`
    unset PW_WINE_VER
    export WINEDIR="${PORT_WINE_PATH}/data/dist/${PW_WINE_USE}"
    export WINE="${WINEDIR}/bin/wine"
    export WINELOADER="${WINEDIR}/bin/wine"
    export WINESERVER="${WINEDIR}/bin/wineserver"
    if [[ -z "${PATH_TO_GAME}" ]] ; then
        export WINEDLLPATH="${WINEDIR}/lib64/wine:${WINEDIR}/lib/wine"
    else
        export WINEDLLPATH="${WINEDIR}/lib64/wine:${WINEDIR}/lib/wine:${PATH_TO_GAME}"
    fi

    if [[ -d "${WINEDIR}/files" && ! -d "${WINEDIR}/dist" ]] ; then
        for clear_dist_files in `ls "${WINEDIR}" | sed -e "s/^files$//g" | sed -e "s/^version$//g"` ; do 
            rm -fr "${WINEDIR}/$clear_dist_files"
        done
        mv -f "${WINEDIR}/files"/* "${WINEDIR}/"
        rm -fr "${WINEDIR}/files"
    elif [[ ! -d "${WINEDIR}/files" && -d "${WINEDIR}/dist" ]] ; then
        for clear_dist_files in `ls "${WINEDIR}" | sed -e "s/^dist$//g" | sed -e "s/^version$//g"` ; do 
            rm -fr "${WINEDIR}/$clear_dist_files"
        done
        mv -f "${WINEDIR}/dist"/* "${WINEDIR}/"
        rm -fr "${WINEDIR}/dist"
    elif [ -f "${WINEDIR}/proton_dist.tar" ] ; then
        unpack_tar "${WINEDIR}/proton_dist.tar" "${WINEDIR}/"
        for clear_dist_files in `ls "${WINEDIR}" | sed -e "s/^bin$//g" | sed -e "s/^lib$//g" | sed -e "s/^lib64$//g" | sed -e "s/^share$//g" | sed -e "s/^version$//g"` ; do 
            rm -fr "${WINEDIR}/$clear_dist_files"
        done
    fi
    if [[ -d "${WINEDIR}" ]] ; then
        [[ ! -f "${WINEDIR}/version" ]] && echo "${PW_WINE_USE}" > "${WINEDIR}/version"

        if [[ ! -d "${WINEDIR}/lib64/" && -d "${WINEDIR}/lib/wine/x86_64-unix" ]] ; then
            create_new_dir "${WINEDIR}/lib64/wine"
            mv -f "${WINEDIR}/lib/wine/x86_64-unix" "${WINEDIR}/lib64/wine/"
            mv -f "${WINEDIR}/lib/wine/x86_64-windows" "${WINEDIR}/lib64/wine/"
        fi
        
        try_remove_file "${WINEDIR}/lib/libsteam_api.so"
        try_remove_file "${WINEDIR}/lib64/libsteam_api.so"
        
        for copy_proton_dll in "dxvk" "vkd3d-proton" ; do
            if [[ ! -d "${WINEDIR}/lib/wine/${copy_proton_dll}/" || ! -d "${WINEDIR}/lib64/wine/${copy_proton_dll}/" ]] ; then
                try_copy_dir "${PORT_WINE_PATH}/data/dist/${PW_PROTON_GE_VER}/lib/wine/${copy_proton_dll}" "${WINEDIR}/lib/wine/"
                try_copy_dir "${PORT_WINE_PATH}/data/dist/${PW_PROTON_GE_VER}/lib64/wine/${copy_proton_dll}" "${WINEDIR}/lib64/wine/"
            fi
        done
        
        for mono_gecko_chk in "mono" "gecko" ; do
            if check_symlink "${WINEDIR}/share/wine/${mono_gecko_chk}" ; then
                echo "${WINEDIR}/share/wine/${mono_gecko_chk} is symlink. OK."
            elif [[ -d "${WINEDIR}/share/wine/${mono_gecko_chk}" ]] ; then
                try_copy_dir "${WINEDIR}/share/wine/${mono_gecko_chk}" "${PORT_WINE_TMP_PATH}" | sszen
                try_remove_dir "${WINEDIR}/share/wine/${mono_gecko_chk}"
                try_force_link_dir "${PORT_WINE_TMP_PATH}/${mono_gecko_chk}" "${WINEDIR}"/share/wine/
                echo "Copy ${WINEDIR}/share/wine/${mono_gecko_chk} to tmp and create symlink to ${WINEDIR}/share/wine/. OK."
            else
                try_remove_dir "${WINEDIR}/share/wine/${mono_gecko_chk}"
                try_force_link_dir "${PORT_WINE_TMP_PATH}/${mono_gecko_chk}" "${WINEDIR}"/share/wine
                echo "${WINEDIR}/share/wine/${mono_gecko_chk} is broken symlink. Repair... OK."
            fi
        done
    fi
    return 0
}

pw_init_runtime () {
    # PW_OS_LIB='opensuse|centos|rosa|altlinux|astra|redos|fedora|gentoo'
    # if [[ ! -z "`cat /etc/*-release | grep -iE "${PW_OS_LIB}"`" ]] ; then
    #     if check_symlink "${PW_WINELIB}/portable/lib/lib64" ; then
    #         rm -fr "${PW_WINELIB}/portable/lib/lib64"
    #     fi
    #     if [[ ! -d "${PW_WINELIB}/portable/lib/lib64" ]] ; then
    #         mv -f "${PW_WINELIB}/portable/lib/lib" "${PW_WINELIB}/portable/lib/lib64"
    #     fi
    #     if [[ ! -d "${PW_WINELIB}/portable/lib/lib" ]] ; then
    #         ln -s "${PW_WINELIB}/portable/lib/lib32" "${PW_WINELIB}/portable/lib/lib"
    #     fi
    # fi

    PW_PV_OVERRIDES="/usr/lib/pressure-vessel/overrides/lib" 
    if [[ ! -z "${LD_LIBRARY_PATH}" ]] ; then
        export PW_LD_LIBRARY_PATH="${WINEDIR}/lib64:${WINEDIR}/lib:${PW_WINELIB}/portable/lib/lib64:${PW_WINELIB}/portable/lib/lib32:${PW_PV_OVERRIDES}/x86_64-linux-gnu/aliases:${PW_PV_OVERRIDES}/i386-linux-gnu/aliases:${LD_LIBRARY_PATH}"
    else
        export PW_LD_LIBRARY_PATH="${WINEDIR}/lib64:${WINEDIR}/lib:${PW_WINELIB}/portable/lib/lib64:${PW_WINELIB}/portable/lib/lib32:${PW_PV_OVERRIDES}/x86_64-linux-gnu/aliases:${PW_PV_OVERRIDES}/i386-linux-gnu/aliases"
    fi 

    export PW_VK_LAYER_PATH="${PW_WINELIB}/portable/share/vulkan/implicit_layer.d/"

    if [ ! -z ${PATH_TMP} ]
    then export PATH="${PATH_TMP}"
    else export PATH_TMP="${PATH}"
    fi
    if [ ! -z "${PATH}" ]
    then export PATH="${WINEDIR}/bin:${PATH}:${PW_WINELIB}/portable/bin"
    else export PATH="${WINEDIR}/bin:${PW_WINELIB}/portable/bin"
    fi
    if [ "${PW_USE_GSTREAMER}" = 1 ] ; then 
        if [ -d "${WINEDIR}/lib64/gstreamer-1.0" ] ; then
            export GST_PLUGIN_SYSTEM_PATH_1_0="${WINEDIR}/lib64/gstreamer-1.0:${WINEDIR}/lib/gstreamer-1.0"
        fi
        export WINE_GST_REGISTRY_DIR="${PORT_WINE_TMP_PATH}"
        export MEDIACONV_AUDIO_DUMP_FILE="${PORT_WINE_TMP_PATH}"/audio.foz
        export MEDIACONV_AUDIO_TRANSCODED_FILE="${PORT_WINE_TMP_PATH}"/transcoded_audio.foz
        export MEDIACONV_VIDEO_DUMP_FILE="${PORT_WINE_TMP_PATH}"/video.foz
        export MEDIACONV_VIDEO_TRANSCODED_FILE="${PORT_WINE_TMP_PATH}"/transcoded_video.foz
    else
        var_winedlloverride_update "winegstreamer="
    fi

    if [[ ! -z "${PW_SANDBOX_HOME_PATH}" && -d "${PW_SANDBOX_HOME_PATH}" ]]; then
        export pw_runtime="${PW_WINELIB}/run \
        --unshare-home \
        --home="${PW_SANDBOX_HOME_PATH}" \
        ${PW_ADD_TO_ARGS_IN_RUNTIME} --"
    else
        export pw_runtime="${PW_WINELIB}/run \
        --share-home \
        ${PW_ADD_TO_ARGS_IN_RUNTIME} --"
    fi

    export PRESSURE_VESSEL_GC_RUNTIMES=1
    export PRESSURE_VESSEL_COPY_RUNTIME=1
    export PRESSURE_VESSEL_GC_LEGACY_RUNTIMES=1
    export PRESSURE_VESSEL_REMOVE_GAME_OVERLAY=1
    export PRESSURE_VESSEL_IMPORT_VULKAN_LAYERS=1

    unset PRESSURE_VESSEL_RUNTIME_ARCHIVE
    export PRESSURE_VESSEL_RUNTIME=runtime
    export PRESSURE_VESSEL_RUNTIME_BASE="${PW_WINELIB}"
    export PRESSURE_VESSEL_VARIABLE_DIR="${PW_WINELIB}/var"
    export PRESSURE_VESSEL_PREFIX="${PW_WINELIB}/pressure-vessel"

    unset PRESSURE_VESSEL_FILESYSTEMS_RO PRESSURE_VESSEL_FILESYSTEMS_RW
    for PWRTMRO in ${PW_RT_MOUNT_RO[*]} ; do
        if [ ! -z "${PRESSURE_VESSEL_FILESYSTEMS_RO}" ]
        then export PRESSURE_VESSEL_FILESYSTEMS_RO="${PRESSURE_VESSEL_FILESYSTEMS_RO}:${PWRTMRO}"
        else export PRESSURE_VESSEL_FILESYSTEMS_RO="${PWRTMRO}"
        fi
    done
    for PWRTMRW in ${PW_RT_MOUNT_RW[*]} ; do
        if [ ! -z "${PRESSURE_VESSEL_FILESYSTEMS_RW}" ]
        then export PRESSURE_VESSEL_FILESYSTEMS_RW="${PRESSURE_VESSEL_FILESYSTEMS_RW}:${PWRTMRW}"
        else export PRESSURE_VESSEL_FILESYSTEMS_RW="${PWRTMRW}"
        fi
    done
    echo "RUNTIME is enabled"
}

pw_mangohud_check () {
    if [[ "${PW_MANGOHUD}" == "1" ]] ; then
        export MANGOHUD=1
        MANGOHUD_LIB_NAME="libMangoHud.so"
        if [[ "${PW_VULKAN_USE}" = "0" ]] ; then 
	        MANGOHUD_LIB_NAME="libMangoHud_dlsym.so:${MANGOHUD_LIB_NAME}"
        fi
        if [[ ! -z "${PW_LD_PRELOAD}" ]]
        then export PW_LD_PRELOAD="${PW_LD_PRELOAD}:${MANGOHUD_LIB_NAME}"
        else export PW_LD_PRELOAD="${MANGOHUD_LIB_NAME}"
        fi
        var_vk_istance_layers_config_update "VK_LAYER_MANGOHUD_overlay64:VK_LAYER_MANGOHUD_overlay32"
        print_info "MANGOHUD is enabled"
    else
        export DISABLE_MANGOHUD=1
        print_info "MANGOHUD is disabled"
    fi
    return 0
}

pw_vkbasalt_check () {
    if [[ "${ENABLE_VKBASALT}" == 1 ]] && [[ "${PW_VULKAN_USE}" != "0" ]] && [[ "${PW_VULKAN_USE}" != "3" ]] ; then
        if [[ -z "${PW_VKBASALT_EFFECTS}" ]] ; then
            export PW_VKBASALT_EFFECTS="cas:FilmGrain2" 
        fi
        sed -ri "s/effects = .*/effects = ${PW_VKBASALT_EFFECTS}/g" "${PORT_WINE_PATH}/data/vkBasalt.conf"
        if [[ -z "${PW_VKBASALT_FFX_CAS}" ]] ; then
            export PW_VKBASALT_FFX_CAS="0.7" 
        fi
        sed -ri "s/casSharpness .*/casSharpness = ${PW_VKBASALT_FFX_CAS}/g" "${PORT_WINE_PATH}/data/vkBasalt.conf"
        export VKBASALT_CONFIG_FILE="${PORT_WINE_PATH}/data/vkBasalt.conf"
        sed -i s/'> = 0.05;'/'> = 0.035;'/ "${PW_WINELIB}/pressure-vessel/reshade/shaders/FilmGrain2.fx"
        sed -i s/'> = 0.65;'/'> = 0.4;'/ "${PW_WINELIB}/pressure-vessel/reshade/shaders/Curves.fx"
        sed -i s/'> = 0.8;'/'> = 0.9;'/ "${PW_WINELIB}/pressure-vessel/reshade/shaders/Bloom.fx"
        var_vk_istance_layers_config_update "VK_LAYER_VKBASALT_post_processing32:VK_LAYER_VKBASALT_post_processing64"
        print_info "vkBasalt is enabled"
    else
        export DISABLE_VKBASALT=1
        print_info "vkBasalt is disabled"
    fi
    return 0
}

check_nvidia_vk_icd_file () {
    if [[ -f "/usr/share/vulkan/icd.d/nvidia_icd.json" ]] ; then
        export VK_ICD_FILENAMES="/usr/share/vulkan/icd.d/nvidia_icd.json"
    elif [[ -f "/etc/vulkan/icd.d/nvidia_icd.json" ]] ; then
        export VK_ICD_FILENAMES="/etc/vulkan/icd.d/nvidia_icd.json"
    fi
}

regdlloverrides () {
    PW_DLL_EXE=`echo $@ | awk -F: '{print $1}'`
    PW_DLL_LIB=`echo $@ | awk -F: '{print $2}' | awk -F= '{print $1}'`
    PW_DLL_SET=`echo $@ | awk -F= '{print $NF}'`
    case "${PW_DLL_SET}" in
        "n,b") PW_DLL_IN_REG="native,builtin" ;;
        "b,n") PW_DLL_IN_REG="builtin,native" ;;
            "n") PW_DLL_IN_REG="native" ;;
            "b") PW_DLL_IN_REG="builtin" ;;
            *) PW_DLL_IN_REG="" ;;
    esac
    grep 'HKCU,Software\\Wine\\AppDefaults\\'"${PW_DLL_EXE}"'\\DllOverrides,'\"${PW_DLL_LIB}\",0x2,\"${PW_DLL_IN_REG}\" "${WINEDIR}/share/wine/wine.inf"
    if [[ "$?" != "0" ]] ; then
        sed -i "/\[SteamClient.ntamd64\]/a HKCU,Software\\\Wine\\\AppDefaults\\\\${PW_DLL_EXE}\\\DllOverrides,\"${PW_DLL_LIB}\",0x2,\"${PW_DLL_IN_REG}\"" "${WINEDIR}/share/wine/wine.inf"
    fi
}

wait_wineserver () {
    while [ ! -z "$(ls -l /proc/*/exe 2>/dev/null | grep -ie ${portname} | grep -E 'wine(64)?-preloader|wineserver' | awk -F/ '{print $3}')" ] ; do
        sleep 1
    done
    return 0
}
export -f wait_wineserver

kill_portwine () {
    wine_pids="`ls -l /proc/*/exe 2>/dev/null | grep -ie ${portname} | grep -E 'wine(64)?-preloader|wineserver' | awk -F/ '{print $3}'`"
    if  [ ! -z "${wine_pids}" ] ; then
        for pw_kill_pids in ${wine_pids} ; do
            if [ "`ps cax | grep ${pw_kill_pids}`" ] ; then
                kill -n 9 ${pw_kill_pids} > /dev/null 2>&1  
            fi
        done
    fi
    bwrap_pids="`pgrep -a wrap | grep ${portname} | head -n 1 | awk '{print $1}'`"
    if  [ ! -z "${bwrap_pids}" ] ; then
        for pw_kill_pids in ${bwrap_pids} ; do
            if [ "`ps cax | grep ${pw_kill_pids}`" ] ; then
                kill -n 9 ${pw_kill_pids} > /dev/null 2>&1
            fi
        done
    fi
    return 0
}
export -f kill_portwine

pw_kill_autostart () {
    if [ "$PW_USE_RUNTIME" != 1 ]
    then print_info "PW_USE_RUNTIME=$PW_USE_RUNTIME"
    else
        sleep 5
        while true ; do
            if  [[ -z "`ps aux | grep -m 1 "$1" | grep -v grep | awk '{print $2}'`" ]] && [[ ! -z "`ps aux | grep wrap | grep -v grep | grep -i ${portname} | head -n 1`" ]] ; then
                echo -e "PID "$1" not found"
                sleep 5
            else
                sleep 5
                kill_portwine 
                break
            fi
        done
    fi
    if [[ ! -z "`ls "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}"/drive_c/ | grep -m 1 ".tmp"`" ]] ; then
        rm -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}"/drive_c/*.tmp
    fi
    return 0
}
export -f pw_kill_autostart

stop_portwine () { 
    if [ "$int_xneur" = "1"  ]; then
        xneur &
    fi
    if [ ! -z ${PW_XKBD} ]; then
        setxkbmap ${PW_XKBD}
    fi
    pw_stop_progress_bar
    try_remove_file "${PORT_SCRIPTS_PATH}/0"
    try_remove_file "${PORT_SCRIPTS_PATH}/1"
    kill_portwine &&
    try_remove_dir "${PW_WINELIB}/var"
    find "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/" -maxdepth 1 -type f -name "*.tmp" -delete
    if [ ! -z "`pgrep -a yad_new | grep "\-\-notification" | awk '{print $1}'`" ] ; then
        kill -s SIGUSR1 "`pgrep -a yad_new | grep "\-\-notification" | awk '{print $1}'`"
    fi
    add_in_stop_portwine > /dev/null 2>&1
    kill -n 9 `pgrep -a start.sh | grep -i '/PortProton/' | awk '{print $1}'` > /dev/null 2>&1
    killall yad_new &>/dev/null
    exit 0
}
export -f stop_portwine

pw_download_libs () {
    if [ ! -z "`ls ${PORT_WINE_TMP_PATH} | grep libs_v | grep -v libs${PW_LIBS_VER}`" ] ; then
        for RM_LIBS in `ls ${PORT_WINE_TMP_PATH} | grep libs_v | grep -v libs${PW_LIBS_VER}`
        do try_remove_dir "${PORT_WINE_TMP_PATH}/${RM_LIBS}"
        done
    fi
    if [[ ! -e "${PW_WINELIB}/portable/bin/yad" || ! -e "${PW_WINELIB}/portable/lib/p7zip/7z" \
    || ! -e "${PW_WINELIB}/runtime/files/bin/vkcube" || -e "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}.tar.xz" ]] ;
    then
        print_info "Download and install libraries..."
        if try_download "github.com/Castro-Fidel/PortWINE/releases/download/libs${PW_LIBS_VER}/libs${PW_LIBS_VER}.tar.xz" "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}.tar.xz" ; then
            if unpack_tar_xz "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}.tar.xz" "${PORT_WINE_TMP_PATH}/" ; then
                try_remove_file "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}.tar.xz"
            else
                try_remove_dir "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}"
                try_remove_file "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}.tar.xz"
                zenity_error_download && pw_download_libs
            fi
        else
            zenity_error_download && pw_download_libs
        fi
    fi
    export pw_yad="${PW_WINELIB}/portable/bin/yad"
    export pw_yad_new="${PW_WINELIB}/portable/bin/yad_new"
    export pw_zstd="${PW_WINELIB}/portable/bin/zstd"
    export pw_7z="${PW_WINELIB}/portable/lib/p7zip/7z"
    if [ -x "`which xterm 2>/dev/null`" ]; then
        export SYS_XTERM=`which xterm`
        export PW_XTERM="${SYS_XTERM} -geometry 159x37 -e"
    else
        export PW_XTERM="${PW_WINELIB}/runtime/files/bin/xterm -geometry 159x37 -e"
    fi
    return 0
}

pw_check_and_download_wine () {
    [ ! -d "${PORT_WINE_PATH}/data/dist/" ] && create_new_dir "${PORT_WINE_PATH}/data/dist"
    if [[ "${PW_WINE_USE}" == "GET-OTHER-WINE" ]] ; then
        gui_proton_downloader
    fi
    if [[ ! -z `echo "${PW_WINE_USE}" | grep "^PROTON_STEAM$"` ]] 
    then export PW_WINE_USE="${PW_PROTON_STEAM_VER}"
    elif [[ ! -z `echo "${PW_WINE_USE}" | grep "^PROTON_GE$"` ]]
    then export PW_WINE_USE="${PW_PROTON_GE_VER}"
    fi
    if [ ! -d "${PORT_WINE_PATH}/data/dist/${PW_WINE_USE}" ] ; then
        print_info "Download and install ${PW_WINE_USE}..."
        if try_download "github.com/Castro-Fidel/wine_builds/releases/download/${PW_WINE_USE}/${PW_WINE_USE}.tar.xz" "${PORT_WINE_PATH}/data/tmp/${PW_WINE_USE}.tar.xz" ; then
            if unpack_tar_xz "${PORT_WINE_PATH}/data/tmp/${PW_WINE_USE}.tar.xz" "${PORT_WINE_PATH}/data/dist/" ; then
                echo "${PW_WINE_USE}" > "${PORT_WINE_PATH}/data/dist/${PW_WINE_USE}/version"
                try_remove_file "${PORT_WINE_PATH}/data/tmp/${PW_WINE_USE}.tar.xz"
                try_remove_dir "${PORT_WINE_PATH}/data/tmp/${PW_WINE_USE}"
            else
                try_remove_file "${PORT_WINE_PATH}/data/tmp/${PW_WINE_USE}.tar.xz"
                try_remove_dir "${PORT_WINE_PATH}/data/tmp/${PW_WINE_USE}"
                try_remove_dir "${PORT_WINE_PATH}/data/dist/${PW_WINE_USE}"

                zenity_error_download && pw_check_and_download_wine
            fi
        else
            zenity_error_download && pw_check_and_download_wine
        fi
    fi
    return 0
}

pw_check_and_download_plugins () {
    if [ ! -z "`ls ${PORT_WINE_TMP_PATH} | grep plugins_v | grep -v plugins${PW_PLUGINS_VER}`" ] ; then
        for RM_PLUGINS in `ls ${PORT_WINE_TMP_PATH} | grep plugins_v | grep -v plugins${PW_PLUGINS_VER}`
        do try_remove_dir "${PORT_WINE_TMP_PATH}/${RM_PLUGINS}"
        done
    fi
    if [[ ! -d "${PW_PLUGINS_PATH}/BattlEye_Runtime" || ! -d "${PW_PLUGINS_PATH}/d3d_extras" \
    || ! -d "${PW_PLUGINS_PATH}/nvapi" || ! -d "${PW_PLUGINS_PATH}/nvml" ]]
    then
        print_info "Download and install plugins${PW_PLUGINS_VER}..."
        if try_download "github.com/Castro-Fidel/wine_builds/releases/download/plugins${PW_PLUGINS_VER}/plugins${PW_PLUGINS_VER}.tar.xz" "${PORT_WINE_TMP_PATH}/plugins${PW_PLUGINS_VER}.tar.xz" ; then
            if unpack_tar_xz "${PORT_WINE_TMP_PATH}/plugins${PW_PLUGINS_VER}.tar.xz" "${PORT_WINE_TMP_PATH}" ; then
                try_remove_file "${PORT_WINE_TMP_PATH}/plugins${PW_PLUGINS_VER}.tar.xz" 
            else
                try_remove_file "${PORT_WINE_TMP_PATH}/plugins${PW_PLUGINS_VER}.tar.xz"
                try_remove_dir "${PORT_WINE_TMP_PATH}/plugins${PW_PLUGINS_VER}"

                zenity_error_download && pw_check_and_download_wine
            fi
        else
            zenity_error_download && pw_check_and_download_wine
        fi
    fi
    return 0
}

pw_init_db () {
    if [ ! -z "${portwine_exe}" ]; then
        export PORTWINE_DB=`echo "${portwine_exe}" | awk -F '/' 'NF>1{print $NF}' | sed s/".exe"/""/gi`
        if [[ -f "${portwine_exe}".ppdb ]] ; then
            export PORTWINE_DB_FILE="${portwine_exe}".ppdb
            . "${PORTWINE_DB_FILE}"
            if [[ -z "`ls -p "${PORT_WINE_PATH}/prefixes/" | grep -e "^${PW_PREFIX_NAME}/"`" ]] ; then
                export PW_PREFIX_NAME=`echo "${portwine_exe}" | awk -F"/prefixes/" '{print $2}' | awk -F"/" '{print $1}'`
                edit_db_from_gui PW_PREFIX_NAME
            fi
        else
            orig_IFS="$IFS"
            IFS=$'\n'
            PW_FIND_DB_FILE=`grep -ilw "#${PORTWINE_DB}.exe" "${PORT_SCRIPTS_PATH}/portwine_db"/* | sed s/".exe"/""/gi`
            if [[ `echo "$PW_FIND_DB_FILE" | wc -l` -gt 1 ]] ; then
                unset ADD_CB_DBFILE
                for PW_CHECK_DB_FILE in $PW_FIND_DB_FILE ; do
                    if [[ -z "${ADD_CB_DBFILE}" ]] ; then
                        export ADD_CB_DBFILE="${PW_CHECK_DB_FILE}"
                    else
                        export ADD_CB_DBFILE="${PW_CHECK_DB_FILE}!${ADD_CB_DBFILE}"
                    fi
                done
                PORTWINE_DB_FILE=`"${pw_yad_new}" --text-align=center --text "${PW_SELECTION_DB_LOC}" --borders=15 --form --center  \
                --title "Database file selection..." --window-icon="$PW_GUI_ICON_PATH/port_proton.png"  --form --separator="" \
                --field="DB FILE: :CB" "${ADD_CB_DBFILE}"`
                if [[ "$?" == "1" || "$?" == "252" ]] ; then exit 0 ; fi
            elif [[ `echo "$PW_FIND_DB_FILE" | wc -l` -eq 1 ]] ; then
                PORTWINE_DB_FILE="${PW_FIND_DB_FILE}"
            fi
            IFS="$orig_IFS"
            if [[ -f "${PW_FIND_DB_FILE}" ]] && [[ -z `grep "^export PW_DISABLED_CREATE_DB=1" "${PW_FIND_DB_FILE}"` ]] ; then
                try_copy_file "${PW_FIND_DB_FILE}" "${portwine_exe}".ppdb
            fi
            export PORTWINE_DB_FILE="${portwine_exe}".ppdb
            if [[ ! -z `echo "${portwine_exe}" | grep "/data/prefixes/"` ]] && \
                [[ -z `echo "${portwine_exe}" | grep "/data/prefixes/DEFAULT/"` ]]
            then 
                export PW_PREFIX_NAME=`echo "${portwine_exe}" | awk -F"/prefixes/" '{print $2}' | awk -F"/" '{print $1}'`
                edit_db_from_gui PW_PREFIX_NAME
            fi
        fi
        if [ ! -z "${PORTWINE_DB_FILE}" ]; then
            . "${PORTWINE_DB_FILE}"
            init_wine_ver &&
            print_info "Use ${PORTWINE_DB_FILE} db file."
        fi
        if [ -z "$PATH_TO_GAME" ] ; then
            export PATH_TO_GAME="$( cd "$( dirname "${portwine_exe}" )" >/dev/null 2>&1 && pwd )"
        fi
    fi
    return 0
}

pw_port_update () {
    ###SCRIPTS UPDATE###
    if [ ! -f "${PORT_WINE_TMP_PATH}/scripts_ver" ] ; then
        echo "2022" > "${PORT_WINE_TMP_PATH}/scripts_ver"
    fi
    export scripts_install_ver=`cat "${PORT_WINE_TMP_PATH}/scripts_ver" | head -n 1`
    curl -s --list-only https://raw.githubusercontent.com/Castro-Fidel/PortWINE/master/data_from_portwine/scripts/var > "${PORT_WINE_TMP_PATH}/curent_var_ver"
    [[ ! -f "${PORT_WINE_TMP_PATH}/scripts_update_notifier" ]] && echo "1" > "${PORT_WINE_TMP_PATH}/scripts_update_notifier"
    read "scripts_update_not" < "${PORT_WINE_TMP_PATH}/scripts_update_notifier"
    if [[ "${scripts_update_not}" == "1" ]] ; then
        export scripts_current_ver=`cat "${PORT_WINE_TMP_PATH}/curent_var_ver" | grep SCRIPTS_NEXT_VERSION | awk -F "=" '{print $2}'`
        print_info "Scripts version in github = ${scripts_current_ver}"
        print_info "Scripts version local = ${scripts_install_ver}"
        if [[ ! -z "${scripts_current_ver}" ]] &&  [[ "${scripts_current_ver}" -gt "${scripts_install_ver}" ]] ; then
            if [[ -f "${PW_WINELIB}/portable/bin/yad_new" ]] ; then
                export pw_yad_new="${PW_WINELIB}/portable/bin/yad_new"
                curl -s --list-only "https://raw.githubusercontent.com/Castro-Fidel/PortWINE/master/data_from_portwine/${PW_CHANGELOG_FILE}" | tee "${PORT_WINE_TMP_PATH}/curent_var_ver" | sszen
                CHANGLOG_NEWS=`cat "${PORT_WINE_TMP_PATH}/curent_var_ver" | sed "/Scripts version ${scripts_install_ver}/,$ d" | sed '1,/---/ d' `
                xcsd=`"${pw_yad_new}" --title "${scripts_upd2} v.${scripts_current_ver}" --window-icon="$PW_GUI_ICON_PATH/port_proton.png" \
                --borders=5 --form --separator='%%%' --width=1000 --height=350 --center \
                --field=":TXT" "${CHANGLOG_NEWS}" \
                --field="   ${scripts_upd3} :CB" "${scripts_upd4}!${scripts_upd5}!${scripts_upd6}" `
                YAD_STATUS="$?"
                if [[ "$YAD_STATUS" == "1" || "$YAD_STATUS" == "252" ]] ; then exit 0 ; fi
                xcsd=`echo "${xcsd}" | awk -F'%%%' '{print $2}'`
            else
                xcsd=`zenity --title  "${scripts_upd1}" --text "${scripts_upd2}" --list --radiolist --height=240 --column="${inst_set}" --column "${scripts_upd3}" \
                TRUE "${scripts_upd4}" \
                FALSE "${scripts_upd5}" \
                FALSE "${scripts_upd6}"`
            fi
            case $xcsd in
                "${scripts_upd4}")
                    echo "######################################################"
                    print_info "Update scripts..."
                    try_remove_file "${PORT_WINE_TMP_PATH}/PortWINE-master.tar.gz"
                    if try_download "github.com/Castro-Fidel/PortWINE/archive/refs/heads/master.tar.gz" "${PORT_WINE_TMP_PATH}/PortWINE-master.tar.gz" ; then
                        if unpack_tar_gz "${PORT_WINE_TMP_PATH}/PortWINE-master.tar.gz" "${PORT_WINE_TMP_PATH}"
                        then
                            create_new_dir "${PORT_WINE_TMP_PATH}/scripts_backup"
                            cd "${PORT_WINE_PATH}/data/"
                            tar -czpf "${PORT_WINE_TMP_PATH}/scripts_backup/scripts_v.${scripts_install_ver}.tar.gz" ./scripts ./img \
                            ./changelog* ./dxvk.conf ./vkBasalt.conf ./tmp/scripts_ver
                            cp -fr "${PORT_WINE_TMP_PATH}/PortWINE-master/data_from_portwine/"* "${PORT_WINE_PATH}/data/"
                            try_remove_file "${PORT_WINE_TMP_PATH}/PortWINE-master.tar.gz"
                            try_remove_dir "${PORT_WINE_TMP_PATH}/PortWINE-master/"
                            echo "${scripts_current_ver}" > "${PORT_WINE_TMP_PATH}/scripts_ver"
                            if [[ -z "${pw_yad_new}" ]] ; then
                                zenity --title="Changelog" --text-info --width=1200 --height=550 \
                                --filename="${PORT_WINE_PATH}/data/${PW_CHANGELOG_FILE}"
                            fi
                            [ "$?" == 0 ] && /usr/bin/env bash -c ${pw_full_command_line[*]} &
                            exit 0
                        fi
                    else
                        zenity_error_download && pw_scripts_update
                    fi ;;
                "${scripts_upd5}")
                    echo " " ;;
                "${scripts_upd6}")
                echo "0" > "${PORT_WINE_TMP_PATH}/scripts_update_notifier" ;;
            esac
        fi
    fi
    try_remove_file "${PORT_WINE_TMP_PATH}/curent_var_ver"
    return 0
}


update_winetricks () {
    W_TRX_URL="raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks"
    W_TRX_EXT_VER="$(curl -s --list-only ${W_TRX_URL} | grep -i 'WINETRICKS_VERSION=' | sed 's/WINETRICKS_VERSION=//')"
    print_info "Version winetricks on server: ${W_TRX_EXT_VER}"
    W_TRX_INT_VER="$(cat "${PORT_WINE_TMP_PATH}/winetricks" | grep -i 'WINETRICKS_VERSION=' | sed 's/WINETRICKS_VERSION=//')"
    print_info "Version winetricks in port: ${W_TRX_INT_VER}"
    if [[ ! -f "${PORT_WINE_TMP_PATH}/winetricks" && ! -z "$W_TRX_EXT_VER" ]] || [[ "$W_TRX_INT_VER" != "$W_TRX_EXT_VER" && ! -z "$W_TRX_EXT_VER" ]]; then
        if try_download "${W_TRX_URL}" "${PORT_WINE_TMP_PATH}/winetricks_new" ; then
            mv -f "${PORT_WINE_TMP_PATH}/winetricks_new" "${PORT_WINE_TMP_PATH}/winetricks"
            W_TRX_INT_VER="$(cat "${PORT_WINE_TMP_PATH}/winetricks" | grep -i 'WINETRICKS_VERSION=' | sed 's/WINETRICKS_VERSION=//')" && print_info "Winetricks version in port has been updated (${W_TRX_INT_VER})" 
            chmod u+x "${PORT_WINE_TMP_PATH}/winetricks"
        fi
    fi
    if  [ -f "${PORT_WINE_TMP_PATH}/winetricks" ] ; then
        sed -i 's/w_metadata vcrun2015 dlls \\/w_metadata !dont_use_2015! dlls \\/' "${PORT_WINE_TMP_PATH}/winetricks"
        sed -i 's/w_metadata vcrun2017 dlls \\/w_metadata !dont_use_2017! dlls \\/' "${PORT_WINE_TMP_PATH}/winetricks"
        #HOTFIX SHA256SUM FOR VC_RUN2019
        sed -i 's/vc_redist.x86.exe 1acd8d5ea1cdc3eb2eb4c87be3ab28722d0825c15449e5c9ceef95d897de52fa/vc_redist.x86.exe 80c7969f4e05002a0cd820b746e0acb7406d4b85e52ef096707315b390927824/g' "${PORT_WINE_TMP_PATH}/winetricks"
        sed -i 's/vc_redist.x64.exe 003063723b2131da23f40e2063fb79867bae275f7b5c099dbd1792e25845872b/vc_redist.x64.exe 9b9dd72c27ab1db081de56bb7b73bee9a00f60d14ed8e6fde45dab3e619b5f04/g' "${PORT_WINE_TMP_PATH}/winetricks"

    fi
    return 0
}

edit_db_from_gui () {
    echo "edit_db_from_gui PORTWINE_DB_FILE=$PORTWINE_DB_FILE"
    for mod_db in $@ ; do
        echo "${mod_db}=${!mod_db}"
        if [ -z "`cat "${PORTWINE_DB_FILE}" | grep "export ${mod_db}="`" ] ; then
            echo "export ${mod_db}=\"${!mod_db}\"" >> "${PORTWINE_DB_FILE}"
        elif [ "`cat "${PORTWINE_DB_FILE}" | grep "export ${mod_db}=" | grep -v "#"`" ] ; then
            if [ "`cat "${PORTWINE_DB_FILE}" | grep "export ${mod_db}=" | grep -v "#"`" != "export ${mod_db}=\"${!mod_db}\"" ] ; then
                sed -ri "s/^export ${mod_db}=.*/export ${mod_db}=\"${!mod_db}\"/" "${PORTWINE_DB_FILE}"
            fi
        elif [ "`cat "${PORTWINE_DB_FILE}" | grep "export ${mod_db}="`" != "export ${mod_db}=${!mod_db}" ] ; then
            sed -ri "s/.*export ${mod_db}=.*/export ${mod_db}=\"${!mod_db}\"/g" "${PORTWINE_DB_FILE}"
        fi
    done
    return 0
}

pw_create_gui_png () {
    if [ ! -z "${PORTWINE_CREATE_SHORTCUT_NAME}" ] ; then
        export PORTPROTON_NAME="${PORTWINE_CREATE_SHORTCUT_NAME}"
    else
        export PORTPROTON_NAME="$(basename "${portwine_exe}" | sed s/".exe"/""/gi )"
    fi
    PW_RESIZE_TO=128
    try_remove_file "${PORT_WINE_PATH}/data/img/setup.png"
    if [[ -x "`which wrestool 2>/dev/null`" ]] && [[ ! -f "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" ]] ; then
        try_remove_dir "${PORT_WINE_TMP_PATH}/tmp_img"
        create_new_dir "${PORT_WINE_TMP_PATH}/tmp_img"
        wrestool -x --output="${PORT_WINE_TMP_PATH}/tmp_img/" -t14 "${portwine_exe}"
        cp "$(ls -S -1 "${PORT_WINE_TMP_PATH}/tmp_img/"*".ico" | head -n 1)" "${PORT_WINE_TMP_PATH}/tmp_img/${PORTPROTON_NAME}.ico"
        icotool -x --width=${PW_RESIZE_TO} --height=${PW_RESIZE_TO} --output="${PORT_WINE_TMP_PATH}/tmp_img/" "${PORT_WINE_TMP_PATH}/tmp_img/${PORTPROTON_NAME}.ico"
        if [[ ! -f "$(ls -S -1 "${PORT_WINE_TMP_PATH}/tmp_img/"*".png" | grep "${PW_RESIZE_TO}x${PW_RESIZE_TO}")" ]] ; then 
            icotool -x --output="${PORT_WINE_TMP_PATH}/tmp_img/" "${PORT_WINE_TMP_PATH}/tmp_img/${PORTPROTON_NAME}.ico"
            cp "$(ls -S -1 "${PORT_WINE_TMP_PATH}/tmp_img/"*".png" | head -n 1)" "${PORT_WINE_TMP_PATH}/tmp_img/${PORTPROTON_NAME}.png"
        else
            cp "$(ls -S -1 "${PORT_WINE_TMP_PATH}/tmp_img/"*".png" | grep "${PW_RESIZE_TO}x${PW_RESIZE_TO}" | head -n 1)" "${PORT_WINE_TMP_PATH}/tmp_img/${PORTPROTON_NAME}.png"
        fi
        cp -f "${PORT_WINE_TMP_PATH}/tmp_img/${PORTPROTON_NAME}.png" "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png"
    fi
    if [[ -z "`file "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" | grep "${PW_RESIZE_TO} x ${PW_RESIZE_TO}"`" ]] && \
       [[ -x "`which "convert" 2>/dev/null`" ]] && [[ -f "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" ]] ; then
        convert "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" -resize ${PW_RESIZE_TO}x${PW_RESIZE_TO} "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" 
    fi
    if [[ -z "${PW_ICON_FOR_YAD}" ]] ; then
        if [[ ! -z "`file "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" | grep "${PW_RESIZE_TO} x ${PW_RESIZE_TO}"`" ]] ; then
            export PW_ICON_FOR_YAD="${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" 
        else
            export PW_ICON_FOR_YAD="${PW_GUI_ICON_PATH}/port_proton.png"
        fi
    fi
}
