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

print_error () {
    printf "\E[31m%s Error: $@ %s\e[0m\n"
}
export -f print_error

fatal () {
    print_error "$@"
    exit 1
}

print_warning () {
    printf "\E[33m%s Warning: $@ %s\e[0m\n"
}
export -f print_warning

print_info () {
    printf "\E[36m%s Info: $@ %s\e[0m\n"
}
export -f print_info

print_ok () {
    printf "\E[35m%s OK: $@ %s\e[0m\n"
}
export -f print_ok

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

check_variables () { [[ -z ${!1} ]] && export $1="$2" ;}

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" ] || [ ! -e "$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 :
    elif [ -z "$2" ] ; then	print_error "no way to link file $1"
    else
        ln -s -f -r "$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 -s -f -r "$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_no_mirror () {
    [[ -f "${PW_AUTOINSTALL_EXE}" ]] && try_remove_file "${PW_AUTOINSTALL_EXE}"
    PW_DOWNLOAD_FILE_NAME="$(basename $2)"
    if check_gamescope_session ; then
        $PW_TERM curl -f -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" \
        -H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' -L "$1" -o "$2"
        [ "$?" != 0 ] && return 1 || return 0
    fi
    set -o pipefail
    curl -f -# -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" -H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' -L "$1" -o "$2" 2>&1 | \
    tr '\r' '\n' | sed -ur 's|[# ]+||g;s|.*=.*||g;s|.*|#Downloading at &\n&|g' | \
    "${pw_yad_v13_0}" --progress --percentage=0 --text="${loc_downloading} ${PW_DOWNLOAD_FILE_NAME}" --auto-close --no-escape \
    --auto-kill --center --text-align="center" --fixed --no-buttons --title "PortProton" --width=500 --height=90 \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --borders=15
    if [ "${PIPESTATUS[0]}" != 0 ] ; then
        print_error "Failed to download $PW_DOWNLOAD_FILE_NAME"
        return 1
    else
        print_ok "File downloaded successfully: $PW_DOWNLOAD_FILE_NAME from $1"
        return 0
    fi
}

try_download () {
    PW_DOWNLOAD_FILE_NAME="$(basename $1)"
    if check_gamescope_session ; then
        $PW_TERM curl -f -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" \
        -H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' -L "$1" -o "$2"
        # $PW_TERM curl -f -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" \
        # -H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' -L "ftp://171.22.215.18/archives/${PW_DOWNLOAD_FILE_NAME}" -o "$2"
        return 0
    fi
    [[ ! -f "${pw_yad_v13_0}" ]] && local pw_yad_v13_0="yad"
    set -o pipefail
    curl -f -# -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" -H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' -L "$1" -o "$2" 2>&1 | \
    tr '\r' '\n' | sed -ur 's|[# ]+||g;s|.*=.*||g;s|.*|#Downloading at &\n&|g' | \
    "${pw_yad_v13_0}" --progress --percentage=0 --text="${loc_downloading} ${PW_DOWNLOAD_FILE_NAME}" --auto-close --no-escape \
    --auto-kill --center --text-align="center" --fixed --no-buttons --title "PortProton" --width=500 --height=90 \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --borders=15
    if [ "${PIPESTATUS[0]}" != 0 ] ; then
        print_error "Failed to download ${PW_DOWNLOAD_FILE_NAME} from GitHub."
        print_info "Try download ${PW_DOWNLOAD_FILE_NAME} from FTP"
        curl -f -# -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" -L "ftp://171.22.215.18/archives/${PW_DOWNLOAD_FILE_NAME}" -o "$2" 2>&1 | \
        tr '\r' '\n' | sed -ur 's|[# ]+||g;s|.*=.*||g;s|.*|#Downloading at &\n&|g' | \
        "${pw_yad_v13_0}" --progress --percentage=0 --text="${loc_downloading} ${PW_DOWNLOAD_FILE_NAME}" --auto-close --no-escape \
        --auto-kill --center --text-align="center" --fixed --no-buttons --title "PortProton" --width=500 --height=90 \
        --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --borders=15
        if [ "${PIPESTATUS[0]}" != 0 ] ; then
            print_error "Failed to download ${PW_DOWNLOAD_FILE_NAME} from FTP."
            return 1
        fi
    fi
    try_remove_file "${PORT_WINE_TMP_PATH}/download_log"
    print_ok "File downloaded successfully: $PW_DOWNLOAD_FILE_NAME from $1"
    return 0
}

try_download_to_path () {
    PW_DOWNLOAD_FILE_NAME="$(basename $1)"
    if check_gamescope_session ; then
        $PW_TERM curl -f -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" \
        -H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' -L "$1" -o "$2/$PW_DOWNLOAD_FILE_NAME"
        [ "$?" != 0 ] && return 1 || return 0
    fi
    set -o pipefail
    curl -f -# -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" -H 'Cache-Control: no-cache, no-store' \
    -H 'Pragma: no-cache' -L "$1" -o "$2/$PW_DOWNLOAD_FILE_NAME" 2>&1 | \
    tr '\r' '\n' | sed -ur 's|[# ]+||g;s|.*=.*||g;s|.*|#Downloading at &\n&|g' | \
    "${pw_yad_v13_0}" --progress --percentage=0 --text="${loc_downloading} ${PW_DOWNLOAD_FILE_NAME}" --auto-close --no-escape \
    --auto-kill --center --text-align="center" --fixed --no-buttons --title "PortProton" --width=500 --height=90 \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --borders=15
    if [ "${PIPESTATUS[0]}" != 0 ] ; then
        print_error "Failed to download $PW_DOWNLOAD_FILE_NAME"
        return 1
    else
        print_ok "File downloaded successfully: $PW_DOWNLOAD_FILE_NAME from $1"
        return 0
    fi
}

try_download_silent () {
    PW_DOWNLOAD_FILE_NAME="$(basename $1)"
    curl -f -sS -A "Mozilla/5.0 (compatible; Konqueror/2.1.1; X11)" -H 'Cache-Control: no-cache, no-store' -H 'Pragma: no-cache' -L "$1" -o "$2"
    if [ "$?" != 0 ] ; then
        print_error "Failed to download $PW_DOWNLOAD_FILE_NAME. Skipping."
        try_remove_file "$2"
        return 1
    else
        print_ok "File downloaded successfully: $PW_DOWNLOAD_FILE_NAME from $1"
        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
}

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

pw_notify_send () {
    if command -v notify-send &>/dev/null ; then
        if [[ -f "$PW_GUI_ICON_PATH/portproton.svg" ]]
        then notify-send -a PortProton -i "$PW_GUI_ICON_PATH/portproton.svg" $@ "${PW_NOTIFY_TEXT}"
        else notify-send -a PortProton $@ "${PW_NOTIFY_TEXT}"
        fi
    fi
}

check_start_from_steam () {
    if [[ "${START_FROM_STEAM}" == 1 ]]
    then return 0
    else return 1
    fi
}

check_gamescope_session () {
    if [[ ! -z "$GAMESCOPE_IN_USE" ]]
    then [[ "$GAMESCOPE_IN_USE" == 1 ]] && return 0 || return 1
    fi
    if echo "${DESKTOP_SESSION}" | grep -i "gamescope" &>/dev/null ; then
        if command -v konsole &>/dev/null
        then export PW_TERM="konsole --hide-menubar --fullscreen -e"
        else export PW_TERM="xdg-terminal"
        fi
        export GAMESCOPE_IN_USE=1
        return 0
    else
        export GAMESCOPE_IN_USE=0
        return 1
    fi
}

check_flatpak () {
    if [[ ! -z "$FLATPAK_IN_USE" ]]
    then [[ "$FLATPAK_IN_USE" == 1 ]] && return 0 || return 1
    fi
    if grep -i "flatpak" /etc/os-release &>/dev/null ; then
        export FLATPAK_IN_USE=1
        return 0
    else
        export FLATPAK_IN_USE=0
        return 1
    fi
}


unpack_tar_zst () {
    set -o pipefail
    unset PW_ZSTD_PORT
    pw_start_progress_bar_cover_block "${PW_GUI_ICON_PATH}/covers/unpacking_${update_loc}.gif"
    if command -v zstd &>/dev/null ; then
        tar -I zstd -xhvf "$1" -C "$2"
        pw_stop_progress_bar_cover_block
        [ "${PIPESTATUS[0]}" != 0 ] && print_error "File $1 unpacking error." && return 1 || return 0
    else
        env LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${PW_PLUGINS_PATH}/portable/lib/lib64:${PW_PLUGINS_PATH}/portable/lib/lib" tar -I "${PW_PLUGINS_PATH}/portable/bin/zstd" -xhvf "$1" -C "$2"
        pw_stop_progress_bar_cover_block
        [ "${PIPESTATUS[0]}" != 0 ] && print_error "File $1 unpacking error." && return 1 || return 0
    fi
}

unpack_tar_xz () {
    if [[ "$3" == "silent" ]] ; then
        tar -Jxhvf "$1" -C "$2" && return 0 || return 1
    else
        set -o pipefail
        pw_start_progress_bar_cover_block "${PW_GUI_ICON_PATH}/covers/unpacking_${update_loc}.gif"
        tar -Jxhvf "$1" -C "$2"
        pw_stop_progress_bar_cover_block
        [ "${PIPESTATUS[0]}" != 0 ] && print_error "File $1 unpacking error." && return 1 || return 0
    fi
}

unpack_tar_gz () {
    set -o pipefail
    pw_start_progress_bar_cover_block "${PW_GUI_ICON_PATH}/covers/unpacking_${update_loc}.gif"
    tar -xhzvf "$1" -C "$2"
    pw_stop_progress_bar_cover_block
    [ "${PIPESTATUS[0]}" != 0 ] && print_error "File $1 unpacking error." && return 1 || return 0
}

unpack_tar () {
    set -o pipefail
    pw_start_progress_bar_cover_block "${PW_GUI_ICON_PATH}/covers/unpacking_${update_loc}.gif"
    tar -xhvf "$1" -C "$2"
    pw_stop_progress_bar_cover_block
    [ "${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}/.dotnet48"
    try_remove_file "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver"
    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 (x86)/Internet Explorer"
    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"
    rm -f "${PORT_WINE_TMP_PATH}"/*.bin
    rm -f "${PORT_WINE_TMP_PATH}"/*.foz
    return 0
}

pw_reinstall_pp () {
    if [[ "${PW_REINSTALL_FROM_TERMINAL}" == 1 ]] ; then
        read -p "Do you want to reinstall PortProton? (Y,y - Yes):   " -n 1 -r
        if [[ ! $REPLY =~ ^[Yy]$ ]]
        then
            echo ""
            exit 1
        fi
    elif ! yad_question "${port_reinstall}"
    then exit 1
    fi
    pw_clear_pfx
    try_remove_dir "${PORT_WINE_PATH}/data/dist"
    create_new_dir "${PORT_WINE_PATH}/data/dist"
    try_remove_dir "${PORT_WINE_TMP_PATH}/VULKAN"
    try_remove_file "${PORT_WINE_TMP_PATH}/scripts_update_notifier"
    try_remove_file "${PORT_WINE_PATH}/data/user.conf"
    try_remove_file "${PORT_WINE_TMP_PATH}/scripts_ver"
    echo
    print_info "Restarting PP for reinstall files..."
    export SKIP_CHECK_UPDATES=0
    /usr/bin/env bash -c ${pw_full_command_line[*]} &
    exit 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}"
        echo "# export DXVK_HUD=full" >> "${USER_CONF}"
        echo "# export GALLIUM_HUD=fps" >> "${USER_CONF}"
    elif grep "optirun_on" "${USER_CONF}" &>/dev/null ; then
        sed -i '/optirun_on/d' "${USER_CONF}"
    fi
}

init_wine_ver () {
    if [[ "${PW_WINE_VER}" == "USE_SYSTEM_WINE" ]]
    then export PW_WINE_USE="USE_SYSTEM_WINE"
    elif [[ "${PW_WINE_VER}" == "GET-OTHER-WINE" ]]
    then gui_proton_downloader
    elif [[ ! -z "${PW_WINE_VER}" ]]
    then export PW_WINE_USE="$PW_WINE_VER"
    fi
    unset PW_WINE_VER

    if [[ "${PW_WINE_USE}" == "USE_SYSTEM_WINE" ]] \
    && command -v wine &>/dev/null ; then
        if ! check_flatpak ; then
            export WINEDIR="$RT_PREFIX/usr"
            export WINE="$RT_PREFIX$(command -v wine)"
            export WINELOADER="$WINE"
            export WINESERVER="$RT_PREFIX$(command -v wineserver)"
            export PW_NO_FSYNC=1
        else
            export WINEDIR="$RT_PREFIX/app"
            export WINE="$RT_PREFIX/app/bin/wine"
            export WINELOADER="$WINE"
            export WINESERVER="$RT_PREFIX/app/bin/wineserver"
            export PW_NO_FSYNC=1
        fi
        unset WINEDLLPATH
    else
        if [[ -d "${PORT_WINE_PATH}/data/dist" ]] ; then
        orig_IFS="$IFS"
        IFS=$'\n'
        for dist_dir in $(ls -1 "${PORT_WINE_PATH}/data/dist/") ; do
            dist_dir_new=`echo "${dist_dir}" | awk '$1=$1' | sed -e s/[[:blank:]]/_/g`
            if [[ ! -d "${PORT_WINE_PATH}/data/dist/${dist_dir_new^^}" ]] ; then
                mv -- "${PORT_WINE_PATH}/data/dist/$dist_dir" "${PORT_WINE_PATH}/data/dist/${dist_dir_new^^}"
            fi
        done
        IFS="$orig_IFS"
        fi
        if [[ -z `ls "${PORT_WINE_PATH}/data/dist/" | grep "${PW_WINE_USE}"` ]] ; then
            if [[ "$PW_WINE_USE" =~ PROTON_LG* ]]
            then export PW_WINE_USE=PROTON_LG
            else export PW_WINE_USE=WINE_LG
            fi
        fi
        if [[ "$PW_WINE_USE" == PROTON_LG ]]
        then export PW_WINE_USE="${PW_PROTON_LG_VER}"
        elif [[ "$PW_WINE_USE" == WINE_LG ]]
        then export PW_WINE_USE="${PW_WINE_LG_VER}"
        fi

        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 [[ -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

            for mono_gecko_chk in "mono" "gecko" ; do
                if check_symlink "${WINEDIR}/share/wine/${mono_gecko_chk}" ; then
                    print_info "${WINEDIR}/share/wine/${mono_gecko_chk} is symlink. OK."
                elif [[ -d "${WINEDIR}/share/wine/${mono_gecko_chk}" ]] ; then
                    pw_start_progress_bar_cover_block "${PW_GUI_ICON_PATH}/covers/loading_${update_loc}.gif"
                    try_copy_dir "${WINEDIR}/share/wine/${mono_gecko_chk}" "${PORT_WINE_TMP_PATH}"
                    try_remove_dir "${WINEDIR}/share/wine/${mono_gecko_chk}"
                    try_force_link_dir "${PORT_WINE_TMP_PATH}/${mono_gecko_chk}" "${WINEDIR}"/share/wine/
                    print_info "Copy ${WINEDIR}/share/wine/${mono_gecko_chk} to tmp and create symlink to ${WINEDIR}/share/wine/. OK."
                    pw_stop_progress_bar_cover_block
                else
                    try_remove_dir "${WINEDIR}/share/wine/${mono_gecko_chk}"
                    try_force_link_dir "${PORT_WINE_TMP_PATH}/${mono_gecko_chk}" "${WINEDIR}"/share/wine
                    print_warning "${WINEDIR}/share/wine/${mono_gecko_chk} is broken symlink. Repair... OK."
                fi
            done

            grep 'Global,"{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}",0x10001,0x00000001' "${WINEDIR}/share/wine/wine.inf" &> /dev/null
            if [[ "$?" != "0" ]] ; then
                echo 'HKLM,Software\NVIDIA Corporation\Global,"{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}",0x10001,0x00000001' >> "${WINEDIR}/share/wine/wine.inf"
                echo 'HKLM,System\ControlSet001\Services\nvlddmkm,"{41FCC608-8496-4DEF-B43E-7D9BD675A6FF}",0x10001,0x00000001' >> "${WINEDIR}/share/wine/wine.inf"
                sed -i '/Steam.exe/d' "${WINEDIR}/share/wine/wine.inf"
                sed -i '/\\Valve\\Steam/d' "${WINEDIR}/share/wine/wine.inf"
                sed -i '/winemenubuilder/d' "${WINEDIR}/share/wine/wine.inf"
            fi
        fi

        rm -f "${WINEDIR}"/lib*/*steam* &>/dev/null
        rm -f "${WINEDIR}"/lib*/wine/*/*steam* &>/dev/null
        rm -f "${WINEDIR}"/lib*/wine/*-windows/winemenubuilder.exe &>/dev/null

        export WINEDLLPATH="${WINEDIR}/lib64/wine:${WINEDIR}/lib/wine"
        if [[ -d "${PATH_TO_GAME}" ]] ; then
            export WINEDLLPATH+=":${PATH_TO_GAME}"
        fi
    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
        create_new_dir "${PORT_WINE_TMP_PATH}"/gstreamer_tmp/
        export WINE_GST_REGISTRY_DIR="${PORT_WINE_TMP_PATH}"/gstreamer_tmp/
        export MEDIACONV_AUDIO_DUMP_FILE="${PORT_WINE_TMP_PATH}"/gstreamer_tmp/audio.foz
        export MEDIACONV_AUDIO_TRANSCODED_FILE="${PORT_WINE_TMP_PATH}"/gstreamer_tmp/transcoded_audio.foz
        export MEDIACONV_VIDEO_DUMP_FILE="${PORT_WINE_TMP_PATH}"/gstreamer_tmp/video.foz
        export MEDIACONV_VIDEO_TRANSCODED_FILE="${PORT_WINE_TMP_PATH}"/gstreamer_tmp/transcoded_video.foz
    else
        # var_winedlloverride_update "winegstreamer="
        echo
    fi

    return 0
}

pw_init_runtime () {
    if [[ "$PW_USE_RUNTIME" != 1 ]] \
    || [[ "$PW_WINE_USE" == "USE_SYSTEM_WINE" ]]
    then
        export pw_runtime=""
        return 0
    fi

    if grep -i -E '(ROSA|RED OS)' "/etc/os-release" &>/dev/null ; then
        export LOCPATH="/run/host/usr/share/locale/"
    elif grep -i "altlinux" "/etc/os-release" &>/dev/null ; then
        export LIBGL_DRIVERS_PATH="/usr/lib/X11/modules/dri:/usr/lib64/X11/modules/dri"
    fi

    PW_PV_OVERRIDES="/usr/lib/pressure-vessel/overrides/lib"

    export PW_LD_LIBRARY_PATH="\
${WINEDIR}/lib64:${WINEDIR}/lib:\
${PW_PLUGINS_PATH}/portable/lib/lib64:\
${PW_PLUGINS_PATH}/portable/lib/lib32:\
${PW_PV_OVERRIDES}/x86_64-linux-gnu/aliases:\
${PW_PV_OVERRIDES}/i386-linux-gnu/aliases:\
/overrides/lib/x86_64-linux-gnu:\
/overrides/lib/i386-linux-gnu"

    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_PLUGINS_PATH}/portable/bin"
    else export PATH="${WINEDIR}/bin:${PW_PLUGINS_PATH}/portable/bin"
    fi

    if [[ ! -z "${PW_SANDBOX_HOME_PATH}" && -d "${PW_SANDBOX_HOME_PATH}" ]] ; then
        export pw_runtime="${PW_WINELIB}/pressure-vessel/bin/pressure-vessel-unruntime \
        --unshare-home \
        --home="${PW_SANDBOX_HOME_PATH}" \
        --remove-game-overlay \
        --share-pid \
        ${PW_ADD_TO_ARGS_IN_RUNTIME} --"
    else
        export pw_runtime="${PW_WINELIB}/pressure-vessel/bin/pressure-vessel-unruntime \
        --share-home \
        --remove-game-overlay \
        --share-pid \
        ${PW_ADD_TO_ARGS_IN_RUNTIME} --"
    fi

    if [[ "$PW_USE_SYSTEM_VK_LAYERS" == "1" ]] ; then
        export PRESSURE_VESSEL_IMPORT_VULKAN_LAYERS=1
        unset PW_VK_LAYER_PATH
    else
        export PRESSURE_VESSEL_IMPORT_VULKAN_LAYERS=0
        export PW_VK_LAYER_PATH="${PW_PLUGINS_PATH}/portable/share/vulkan/implicit_layer.d"
    fi

    # export PRESSURE_VESSEL_GRAPHICS_PROVIDER="/"

    unset PRESSURE_VESSEL_RUNTIME_ARCHIVE
    export PRESSURE_VESSEL_COPY_RUNTIME=1
    export PRESSURE_VESSEL_GC_LEGACY_RUNTIMES=1
    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"
    export FONTCONFIG_PATH=''

    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

    # drop portable: libssl 32-bit
    try_remove_file "${PW_PLUGINS_PATH}/portable/lib/lib32/libssl.so.1.1"
    print_info "RUNTIME is enabled"
}

pw_mangohud_check () {
    if [[ "${PW_MANGOHUD}" == "1" ]] \
    && ! check_gamescope_session
    then
        export PW_MANGOHUD_SLR='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 "Portable MANGOHUD is enabled"
    else
        export PW_MANGOHUD_SLR=""
        print_info "Portable MANGOHUD is disabled"
    fi
    return 0
}

pw_vkbasalt_check () {
    if [[ "${ENABLE_VKBASALT}" == 1 ]] && [[ "${PW_VULKAN_USE}" != "0" ]] && [[ "${PW_VULKAN_USE}" != "3" ]] ; then
        export VKBASALT_CONFIG_FILE="${PORT_WINE_PATH}/data/vkBasalt.conf"
        if ! grep "${PW_PLUGINS_PATH}/reshade" "${VKBASALT_CONFIG_FILE}" &>/dev/null
        then sed -ri "s|= .*/reshade|= \"${PW_PLUGINS_PATH}\"/reshade|g" "${VKBASALT_CONFIG_FILE}"
        fi
        if [[ ! -z "${PW_VKBASALT_EFFECTS}" ]] && [[ ! -z "${PW_VKBASALT_FFX_CAS}" ]] ; then
            sed -ri "s/effects = .*/effects = ${PW_VKBASALT_EFFECTS}/g" "${VKBASALT_CONFIG_FILE}"
            sed -ri "s/casSharpness .*/casSharpness = ${PW_VKBASALT_FFX_CAS}/g" "${VKBASALT_CONFIG_FILE}"
        fi
        var_vk_istance_layers_config_update "VK_LAYER_VKBASALT_post_processing64:VK_LAYER_VKBASALT_post_processing32"
        print_info "vkBasalt is enabled"
    else
        export DISABLE_VKBASALT=1
        print_info "vkBasalt is disabled"
    fi
    return 0
}

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
        grep "ProtonOverrides" "${WINEDIR}/share/wine/wine.inf"
        if [[ "$?" == "0" ]] ; then
            sed -i "/\[ProtonOverrides\]/a HKCU,Software\\\Wine\\\AppDefaults\\\\${PW_DLL_EXE}\\\DllOverrides,\"${PW_DLL_LIB}\",0x2,\"${PW_DLL_IN_REG}\"" "${WINEDIR}/share/wine/wine.inf"
        else
            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
    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
    "$WINESERVER" -w
    return 0
}
export -f wait_wineserver

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

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

pw_kill_autostart () {
    if [[ -z "${2}" ]]
    then SWAIT=5
    else SWAIT="${2}"
    fi
    sleep 5
    while true ; do
        if  [[ -z "`ps aux | grep -m 1 -i "$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 "${SWAIT}"
        else
            sleep "${SWAIT}"
            if [[ "$3" == please ]]
            then kill -s SIGTERM `ps aux | grep -m 1 -i "$1" | grep -v grep | awk '{print $2}'`
            else kill_portwine
            fi
            break
        fi
    done

    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 () {
    [[ "$int_xneur" == "1"  ]] && xneur &

    if [[ "$PW_USE_US_LAYOUT" == "1" ]] \
    && [[ "${XDG_SESSION_TYPE}" != "wayland" ]] \
    && command -v setxkbmap &>/dev/null
    then
        setxkbmap
    fi

    if [[ "${XDG_SESSION_TYPE}" != "wayland" ]] \
    && [[ "$(xrandr | sed -rn 's/^.*primary.* ([0-9]+x[0-9]+).*$/\1/p')" != "$PW_SCREEN_RESOLUTION" ]]
    then
        xrandr --output "$PW_SCREEN_PRIMARY" --mode "$PW_SCREEN_RESOLUTION"
    fi

    if [[ "${PW_DISABLE_COMPOSITING}" == "1" ]] \
    && ! check_gamescope_session
    then
        if [[ "${DESKTOP_SESSION}" =~ "plasma" ]] ; then
            qdbus org.kde.KWin /Compositor resume
        elif [[ "${DESKTOP_SESSION}" =~ "mate" ]] ; then
            gsettings set org.mate.Marco.general compositing-manager true
        elif [[ "${DESKTOP_SESSION}" =~ "xfce" ]] ; then
            xfconf-query -c xfwm4 -p /general/use_compositing -s true
        elif [[ "${DESKTOP_SESSION}" =~ "cinnamon" ]] ; then
            gsettings set org.cinnamon.muffin unredirect-fullscreen-windows false
        fi
    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_v13_0 | grep "\--notification" | awk '{print $1}')" ]] ; then
        kill -s SIGUSR1 "`pgrep -a yad_v13_0 | grep "\--notification" | awk '{print $1}'`" 2>/dev/null
    fi
    add_in_stop_portwine #&>/dev/null
    kill -n 9 `pgrep -a start.sh | grep -i '/PortProton/' | awk '{print $1}'` > /dev/null 2>&1
    killall yad_v13_0 &>/dev/null
    exit 0
}
export -f stop_portwine

pw_download_libs () {
    if [[ ! -f "${PW_WINELIB}/runtime/files/bin/vkcube" ]] \
    || [[ ! -f "${PW_WINELIB}/pressure-vessel/bin/pressure-vessel-wrap" ]]
    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"
                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
            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"
                if yad_error_download
                then pw_download_libs
                else
                    export PW_LIBS_VER="$(echo _v$(($(echo $PW_LIBS_VER | sed 's/_v//') - 1)))"
                    export PW_WINELIB="${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}"
                fi
            fi
        else
            if yad_error_download
            then pw_download_libs
            else
                export PW_LIBS_VER="$(echo _v$(($(echo $PW_LIBS_VER | sed 's/_v//') - 1)))"
                export PW_WINELIB="${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}"
            fi
        fi
    fi
    try_remove_dir "${PW_WINELIB}/portable"
    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 [[ "$PW_WINE_USE" == PROTON_LG ]]
    then export PW_WINE_USE="${PW_PROTON_LG_VER}"
    elif [[ "$PW_WINE_USE" == WINE_*_LG ]] || [[ "$PW_WINE_USE" == WINE_LG ]]
    then export PW_WINE_USE="${PW_WINE_LG_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}"

                yad_error_download && pw_check_and_download_wine || exit 1
            fi
        else
            yad_error_download && pw_check_and_download_wine || exit 1
        fi
    fi
    return 0
}

pw_check_and_download_dxvk_and_vkd3d () {
    #Download stable and git version DXVK
    for DXVK_VAR_VER in "${DXVK_STABLE_VER}" "${DXVK_GIT_VER}" ; do
        if [ ! -d "${PW_VULKAN_DIR}/dxvk-${DXVK_VAR_VER}" ] ; then
            print_info "Download and install DXVK v.${DXVK_VAR_VER}"
            if try_download "https://github.com/Castro-Fidel/vulkan/releases/download/dxvk-${DXVK_VAR_VER}/dxvk-${DXVK_VAR_VER}.tar.xz" \
                                      "${PW_VULKAN_DIR}/dxvk-${DXVK_VAR_VER}.tar.xz" ; then
                if unpack_tar_xz "${PW_VULKAN_DIR}/dxvk-${DXVK_VAR_VER}.tar.xz" "${PW_VULKAN_DIR}" ; then
                    try_remove_file "${PW_VULKAN_DIR}/dxvk-${DXVK_VAR_VER}.tar.xz"
                else
                    try_remove_file "${PW_VULKAN_DIR}/dxvk-${DXVK_VAR_VER}.tar.xz"
                    try_remove_dir dxvk-${DXVK_VAR_VER}

                    yad_error_download && pw_check_and_download_dxvk_and_vkd3d || exit 1
                fi
            elif try_download_no_mirror "https://github.com/doitsujin/dxvk/releases/download/v${DXVK_VAR_VER}/dxvk-${DXVK_VAR_VER}.tar.gz" \
                                       "${PW_VULKAN_DIR}/dxvk-${DXVK_VAR_VER}.tar.gz" ; then
                if unpack_tar_gz "${PW_VULKAN_DIR}/dxvk-${DXVK_VAR_VER}.tar.gz" "${PW_VULKAN_DIR}" ; then
                    try_remove_file "${PW_VULKAN_DIR}/dxvk-${DXVK_VAR_VER}.tar.gz"
                else
                    try_remove_file "${PW_VULKAN_DIR}/dxvk-${DXVK_VAR_VER}.tar.gz"
                    try_remove_dir dxvk-${DXVK_VAR_VER}

                    yad_error_download && pw_check_and_download_dxvk_and_vkd3d || exit 1
                fi
            else
                yad_error_download && pw_check_and_download_dxvk_and_vkd3d || exit 1
            fi
        fi
    done

    #Download stable and git version VKD3D
    for VKD3D_VAR_VER in "${VKD3D_STABLE_VER}" "${VKD3D_GIT_VER}" ; do
        if [ ! -d "${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_VAR_VER}" ] ; then
            print_info "Download and install VKD3D-PROTON v.${VKD3D_VAR_VER}"
            if try_download "https://github.com/Castro-Fidel/vulkan/releases/download/vkd3d-proton-${VKD3D_VAR_VER}/vkd3d-proton-${VKD3D_VAR_VER}.tar.xz" \
                                      "${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_VAR_VER}.tar.xz" ; then
                if unpack_tar_xz "${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_VAR_VER}.tar.xz" "${PW_VULKAN_DIR}" ; then
                    try_remove_file "${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_VAR_VER}.tar.xz"
                else
                    try_remove_file "${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_VAR_VER}.tar.xz"
                    try_remove_dir vkd3d-proton-${VKD3D_VAR_VER}

                    yad_error_download && pw_check_and_download_dxvk_and_vkd3d || exit 1
                fi
            elif try_download_no_mirror "https://github.com/HansKristian-Work/vkd3d-proton/releases/download/v${VKD3D_VAR_VER}/vkd3d-proton-${VKD3D_VAR_VER}.tar.zst" \
                                        "${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_VAR_VER}.tar.zst" ; then
                if unpack_tar_zst "${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_VAR_VER}.tar.zst" "${PW_VULKAN_DIR}" ; then
                    try_remove_file "${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_VAR_VER}.tar.zst"
                else
                    try_remove_file "${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_VAR_VER}.tar.zst"
                    try_remove_dir vkd3d-proton-${VKD3D_VAR_VER}

                    yad_error_download && pw_check_and_download_dxvk_and_vkd3d || exit 1
                fi
            else
                yad_error_download && pw_check_and_download_dxvk_and_vkd3d || exit 1
            fi
        fi
    done

    #Download D8VK
    if [ ! -d "${PW_VULKAN_DIR}/d8vk-${D8VK_VER}" ] ; then
        print_info "Download and install D8VK v.${D8VK_VER}"
        if try_download "https://github.com/Castro-Fidel/vulkan/releases/download/d8vk-${D8VK_VER}/d8vk-${D8VK_VER}.tar.xz" "${PW_VULKAN_DIR}/d8vk-${D8VK_VER}.tar.xz" ; then
            if unpack_tar_xz "${PW_VULKAN_DIR}/d8vk-${D8VK_VER}.tar.xz" "${PW_VULKAN_DIR}" ; then
                try_remove_file "${PW_VULKAN_DIR}/d8vk-${D8VK_VER}.tar.xz"
            else
                try_remove_file "${PW_VULKAN_DIR}/d8vk-${D8VK_VER}.tar.xz"
                try_remove_dir "d8vk-${D8VK_VER}"

                yad_error_download && pw_check_and_download_dxvk_and_vkd3d || exit 1
            fi
        else
            yad_error_download && pw_check_and_download_dxvk_and_vkd3d || exit 1
        fi
    fi

    return 0
}

pw_check_and_download_plugins () {
    if [[ ! -f "${PW_PLUGINS_PATH}/portable/bin/yad_new" ]] \
    || [[ ! -f "${PW_PLUGINS_PATH}/portable/bin/yad_v13_0" ]]
    then
        print_info "Download and install plugins${PW_PLUGINS_VER}..."
        if command -v yad &>/dev/null ; then
            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"
                    # TODO: drop clear prefix, and add update prefix from new plugins
                    pw_clear_pfx
                    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
                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}"
                    if yad_error_download
                    then pw_check_and_download_plugins
                    else
                        export PW_PLUGINS_VER="$(echo _v$(($(echo $PW_PLUGINS_VER | sed 's/_v//') - 1)))"
                        export PW_PLUGINS_PATH="${PORT_WINE_TMP_PATH}/plugins${PW_PLUGINS_VER}"
                    fi
                fi
            else
                if yad_error_download
                then pw_check_and_download_plugins
                else
                    export PW_PLUGINS_VER="$(echo _v$(($(echo $PW_PLUGINS_VER | sed 's/_v//') - 1)))"
                    export PW_PLUGINS_PATH="${PORT_WINE_TMP_PATH}/plugins${PW_PLUGINS_VER}"
                fi
            fi
        else
            PW_NOTIFY_TEXT="Please wait for update PortProton"
            pw_notify_send -u normal
            if try_download_silent "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"
                    # TODO: drop clear prefix, and add update prefix from new plugins
                    pw_clear_pfx
                    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
                else
                    PW_NOTIFY_TEXT="Failed updating PortProton!"
                    pw_notify_send -u critical
                    print_error "Failed updating PortProton!"
                fi
            fi
        fi
    fi
    export pw_yad="${PW_PLUGINS_PATH}/portable/bin/yad"
    export pw_yad_v13_0="${PW_PLUGINS_PATH}/portable/bin/yad_v13_0"
    export pw_zstd="${PW_PLUGINS_PATH}/portable/bin/zstd"
    export pw_7z="${PW_PLUGINS_PATH}/portable/lib/p7zip/7z"
    return 0
}

check_dirs_and_files_in_pfx () {
        create_new_dir "${WINEPREFIX}/dosdevices"
        create_new_dir "${WINEPREFIX}/drive_c/windows/syswow64/"
        create_new_dir "${WINEPREFIX}/drive_c/windows/system32/"
        create_new_dir "${WINEPREFIX}/drive_c/tmp/.private/$USER/"
        create_new_dir "${WINEPREFIX}/drive_c/tmp/.private/steamuser/"

        [ ! -d "${WINEPREFIX}/dosdevices/c:" ] && try_force_link_dir "${WINEPREFIX}/drive_c/" "${WINEPREFIX}/dosdevices/c:"
        [ ! -d "${WINEPREFIX}/dosdevices/z:" ] && try_force_link_dir "/" "${WINEPREFIX}/dosdevices/z:"
        [ ! -d "${WINEPREFIX}/dosdevices/h:" ] && try_force_link_dir "$HOME" "${WINEPREFIX}/dosdevices/h:"

        create_new_dir "${WINEPREFIX}/drive_c/windows/Fonts/"
        LN_FONTS="arialbd.ttf courbd.ttf georgia.ttf micross.ttf msyh.ttf simsun.ttc arial.ttf cour.ttf malgun.ttf msgothic.ttc nirmala.ttf times.ttf"
        for link_font in $LN_FONTS ; do
            if [[ ! -f "${WINEPREFIX}/drive_c/windows/Fonts/${link_font}" ]] ; then
                try_force_link_file "${WINEDIR}/share/fonts/${link_font}" "${WINEPREFIX}/drive_c/windows/Fonts/"
            fi
        done

        create_new_dir "${WINEPREFIX}/drive_c/users/steamuser"
        if [[ ! -d "${WINEPREFIX}/drive_c/users/${USER}" ]]
        then try_force_link_dir "${WINEPREFIX}/drive_c/users/steamuser" "${WINEPREFIX}/drive_c/users/${USER}"
        fi

        create_new_dir "${WINEPREFIX}/drive_c/users/Public/Documents/Steam"
        create_new_dir "${WINEPREFIX}/drive_c/users/steamuser/Documents/Steam"
        if [[ ! -d "${WINEPREFIX}/drive_c/users/steamuser/My Documents" ]]
        then try_force_link_dir "${WINEPREFIX}/drive_c/users/steamuser/Documents" "${WINEPREFIX}/drive_c/users/steamuser/My Documents"
        fi

        create_new_dir "${WINEPREFIX}/drive_c/users/steamuser/AppData/Roaming"
        if [[ ! -d "${WINEPREFIX}/drive_c/users/steamuser/Application Data" ]]
        then try_force_link_dir "${WINEPREFIX}/drive_c/users/steamuser/AppData/Roaming" "${WINEPREFIX}/drive_c/users/steamuser/Application Data"
        fi

        create_new_dir "${WINEPREFIX}/drive_c/users/steamuser/AppData/Local"
        create_new_dir "${WINEPREFIX}/drive_c/users/steamuser/Local Settings"
        if [[ ! -d "${WINEPREFIX}/drive_c/users/steamuser/Local Settings/Application Data" ]]
        then try_force_link_dir "${WINEPREFIX}/drive_c/users/steamuser/AppData/Local" "${WINEPREFIX}/drive_c/users/steamuser/Local Settings/Application Data"
        fi

        find "${WINEPREFIX}/dosdevices" -xtype l -maxdepth 1 2>/dev/null -exec rm {} \;
        rm -f "${WINEPREFIX}/dosdevices/"*::
        DRIVES=(d e f g i j k l m n o p q r s t u v w x y)
        DEF_MOUNT_DIRS=('/media' "/media/$USER" '/mnt' '/run/media' "/run/media/$USER")
        MOUNT_DIRS=($(find "${DEF_MOUNT_DIRS[@]}" -maxdepth 1 -type d 2>/dev/null | sort -u))

        for drive_dir in "${MOUNT_DIRS[@]}" ; do
            if [[ ! "${DEF_MOUNT_DIRS[@]}" =~ "$drive_dir" ]] \
            && ! realpath "${WINEPREFIX}/dosdevices"/*: | grep "$drive_dir" &>/dev/null ; then
                drive_num=0
                while [[ "$drive_num" -lt "${#DRIVES[@]}" ]] ; do
                    drive_path="${WINEPREFIX}/dosdevices/${DRIVES[$drive_num]}:"
                    if [ ! -d "$drive_path" ] ; then
                        ln -sf "$drive_dir" "$drive_path"
                        break
                    else
                        ((drive_num++))
                    fi
                done
            fi
        done

        LIST_COPY_WIN_DLL="ntdll shell32"
        for copy_win_dll in $LIST_COPY_WIN_DLL ; do
            try_copy_file "${WINEDIR}/lib64/wine/x86_64-windows/${copy_win_dll}.dll" "${WINEPREFIX}/drive_c/windows/system32/${copy_win_dll}.dll"
            try_copy_file "${WINEDIR}/lib/wine/i386-windows/${copy_win_dll}.dll" "${WINEPREFIX}/drive_c/windows/syswow64/${copy_win_dll}.dll"
        done
    }

check_nvidia_rtx () {
    if [[ ! -z $(echo "$LSPCI_VGA" | grep -i "nvidia") ]]; then
        # Turing (without nvidia 16XX)
        [[ "$LSPCI_VGA" == *TU[0-9]* ]] && [[ "$LSPCI_VGA" != *TU11[6-7]* ]] && return 0
        # Ampere
        [[ "$LSPCI_VGA" == *GA[0-9]* ]] && return 0
        # Ada_Lovelace
        [[ "$LSPCI_VGA" == *AD[0-9]* ]] || [[ "$LSPCI_VGA" == *2[6-8][0-9]* ]] && return 0
    fi
    return 1
}

pw_init_db () {
    if [[ -f "${portwine_exe}" ]] ; then
        export PORTWINE_DB="$(basename "${portwine_exe}" .exe)"
        if [[ -f "${portwine_exe}".ppdb ]] && [[ "${PORTWINE_DB}" != "RiotClientServices" ]] ; 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="`echo ${PW_CHECK_DB_FILE} | awk -F'/' '{print $NF}'`"
                    else
                        export ADD_CB_DBFILE="`echo ${PW_CHECK_DB_FILE} | awk -F'/' '{print $NF}'`!${ADD_CB_DBFILE}"
                    fi
                done
                PORTWINE_DB_FILE="${PORT_SCRIPTS_PATH}/portwine_db"/`"${pw_yad_v13_0}" --text-align=center \
                --text "${PW_SELECTION_DB_LOC}" --borders="${YAD_BORDERS}" --form \
                --title "Database file selection..." --window-icon="$PW_GUI_ICON_PATH/portproton.svg"  --form --separator="" \
                --field="DB FILE: :CB" "${ADD_CB_DBFILE}" 2>/dev/null`
                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
                export PORTWINE_DB_FILE="${portwine_exe}".ppdb
            fi
            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}'`
            fi
        fi
        if [[ -f "${PORTWINE_DB_FILE}" ]] ; then
            . "${PORTWINE_DB_FILE}"
            init_wine_ver &&
            print_info "Use ${PORTWINE_DB_FILE} db file."
        fi
        if [[ -z "${PATH_TO_GAME}" ]] || [[ ! -d "${PATH_TO_GAME}" ]]; then
            export PATH_TO_GAME="$( cd "$( dirname "${portwine_exe}" )" >/dev/null 2>&1 && pwd )"
        fi

        if [[ "${PW_WINE_CPU_TOPOLOGY}" == "disabled" ]] && [[ ! -z "${WINE_CPU_TOPOLOGY}" ]] ; then
            export PW_WINE_CPU_TOPOLOGY="${WINE_CPU_TOPOLOGY}"
        fi
        if ls "${PATH_TO_GAME}"/*_Data/Resources/ 2>/dev/null | grep "unity" &>/dev/null \
        && [[ "${PW_WINE_CPU_TOPOLOGY}" == "disabled" ]] \
        && [[ $(grep -c "^processor" /proc/cpuinfo) -gt "8" ]]
        then
                export PW_WINE_CPU_TOPOLOGY="8:0,1,2,3,4,5,6,7"
                print_info "Automatic added fix for unity games: WINE_CPU_TOPOLOGY=8:0,1,2,3,4,5,6,7"
        fi

        if check_nvidia_rtx ; then
            check_variables PW_USE_NVAPI_AND_DLSS "1"
            check_variables PW_USE_FAKE_DLSS "0"
            check_variables PW_USE_RAY_TRACING "1"
        fi

        if grep "RUS" "${PORT_WINE_TMP_PATH}/${portname}_loc" &>/dev/null ; then
            for chk_lang_and_uname in "steam_emu.ini" "steam_api.ini" "steam_api64.ini" ; do
                if [[ -f "${PATH_TO_GAME}/${chk_lang_and_uname}" ]] ; then
                    sed -i "s/Language=english/Language=russian/" "${PATH_TO_GAME}/${chk_lang_and_uname}"
                    sed -i "/UserName=/c\UserName=${USER}" "${PATH_TO_GAME}/${chk_lang_and_uname}"
                fi
            done
        fi
    fi
    [[ "${START_FROM_STEAM}" == 1 ]] && export PW_GUI_DISABLED_CS=1
    [[ "${START_FROM_PP_GUI}" == 1 ]] && export PW_GUI_DISABLED_CS=0 && unset START_FROM_PP_GUI

    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`
    print_info "Check update..."
    if curl -f -s --list-only --connect-timeout 3 "https://raw.githubusercontent.com/Castro-Fidel/PortWINE/master/data_from_portwine/scripts/var" > "${PORT_WINE_TMP_PATH}/curent_var_ver"
    then
        URL_FOR_CHANGELOG="https://raw.githubusercontent.com/Castro-Fidel/PortWINE/master/data_from_portwine"
        URL_TO_PW_MASTER="https://github.com/Castro-Fidel/PortWINE/archive/refs/heads/master.tar.gz"
        print_info "OK."
    else
        if curl -f -s --list-only --connect-timeout 3 "https://gitlab.eterfund.ru/Castro-Fidel/PortWINE/raw/master/data_from_portwine/scripts/var" > "${PORT_WINE_TMP_PATH}/curent_var_ver"
        then
            URL_FOR_CHANGELOG="https://gitlab.eterfund.ru/Castro-Fidel/PortWINE/raw/master/data_from_portwine"
            URL_TO_PW_MASTER="https://gitlab.eterfund.ru/Castro-Fidel/PortWINE/-/archive/master/PortWINE-master.tar.gz"
            print_info "OK."
        else
            print_error "Unable to determine the version on the server. Skip it..."
            return 1
        fi
    fi
    [[ ! -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_PLUGINS_PATH}/portable/bin/yad_v13_0" ]]
            then export pw_yad_v13_0="${PW_PLUGINS_PATH}/portable/bin/yad_v13_0"
            elif command -v yad &>/dev/null
            then local pw_yad_v13_0="yad"
            else local pw_yad_v13_0="not_found"
            fi
            if [[ "${pw_yad_v13_0}" == "not_found" ]] ; then
                xcsd="${scripts_upd4}"
            else
                curl -s --list-only "${URL_FOR_CHANGELOG}/${PW_CHANGELOG_FILE}" | tee "${PORT_WINE_TMP_PATH}/curent_var_ver"
                CHANGLOG_NEWS=`cat "${PORT_WINE_TMP_PATH}/curent_var_ver" | sed "/Scripts version ${scripts_install_ver}/,$ d" | sed '1,/---/ d' `
                xcsd=`"${pw_yad_v13_0}" --title "${scripts_upd2} v.${scripts_current_ver}" --window-icon="$PW_GUI_ICON_PATH/portproton.svg" \
                --form --separator='%%%' --width=1200 --height=600 \
                --field=":TXT" "${CHANGLOG_NEWS}" \
                --field="   ${scripts_upd3} :CB" "${scripts_upd4}!${scripts_upd5}!${scripts_upd6}" 2>/dev/null`
                YAD_STATUS="$?"
                if [[ "$YAD_STATUS" == "1" || "$YAD_STATUS" == "252" ]] ; then exit 0 ; fi
                xcsd=`echo "${xcsd}" | awk -F'%%%' '{print $2}'`
            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_no_mirror "${URL_TO_PW_MASTER}" "${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
                            try_remove_dir "${PORT_WINE_PATH}/data/scripts/portwine_db"
                            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"
                            echo "Restarting PP after update..."
                            export SKIP_CHECK_UPDATES=1
                            /usr/bin/env bash -c ${pw_full_command_line[*]} &
                            exit 0
                        fi
                    else
                        yad_error_download && pw_port_update || exit 1
                    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="https://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
        try_remove_file "${PORT_WINE_TMP_PATH}/winetricks"
        if try_download_no_mirror "${W_TRX_URL}" "${PORT_WINE_TMP_PATH}/winetricks" ; then
            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"
        sed -i 's/w_metadata vcrun2019 dlls \\/w_metadata !dont_use_2019! dlls \\/' "${PORT_WINE_TMP_PATH}/winetricks"
        sed -i 's/w_set_winver win2k3/w_set_winver win7/' "${PORT_WINE_TMP_PATH}/winetricks"
    fi
    return 0
}

edit_db_from_gui () {
    print_info "edit_db_from_gui PORTWINE_DB_FILE=$PORTWINE_DB_FILE"
    for mod_db in $@ ; do
        if ! grep "export ${mod_db}=" "${PORTWINE_DB_FILE}" &>/dev/null
        then echo "export ${mod_db}=\"${!mod_db}\"" >> "${PORTWINE_DB_FILE}"
        elif grep "export ${mod_db}=" "${PORTWINE_DB_FILE}" | grep -v "#" &>/dev/null
        then
            if [[ "$(grep "export ${mod_db}=" "${PORTWINE_DB_FILE}" | grep -v "#")" != "export ${mod_db}=\"${!mod_db}\"" ]]
            then sed -ri "s|^export ${mod_db}=.*|export ${mod_db}=\"${!mod_db}\"|" "${PORTWINE_DB_FILE}"
            fi
        elif [[ "$(grep "export ${mod_db}=" "${PORTWINE_DB_FILE}")" != "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
}

edit_user_conf_from_gui () {
    for mod_db in $@ ; do
        if ! grep "export ${mod_db}=" "${USER_CONF}" &>/dev/null
        then echo "export ${mod_db}=\"${!mod_db}\"" >> "${USER_CONF}"
        elif grep "export ${mod_db}=" "${USER_CONF}" | grep -v "#" &>/dev/null
        then
            if [[ "$(grep "export ${mod_db}=" "${USER_CONF}" | grep -v "#")" != "export ${mod_db}=\"${!mod_db}\"" ]]
            then sed -ri "s/^export ${mod_db}=.*/export ${mod_db}=\"${!mod_db}\"/" "${USER_CONF}"
            fi
        elif [[ "$(grep "export ${mod_db}=" "${USER_CONF}")" != "export ${mod_db}=${!mod_db}" ]]
        then sed -ri "s/.*export ${mod_db}=.*/export ${mod_db}=\"${!mod_db}\"/g" "${USER_CONF}"
        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"
    try_remove_file "${PORT_WINE_PATH}/data/img/Setup.png"
    try_remove_file "${PORT_WINE_PATH}/data/img/launcher.png"
    try_remove_file "${PORT_WINE_PATH}/data/img/Launcher.png"
    if [[ ! -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"
        if command -v wrestool &>/dev/null ; then
            wrestool -x --output="${PORT_WINE_TMP_PATH}/tmp_img/" -t14 "$(readlink -f "${portwine_exe}")"
        else
            env LD_LIBRARY_PATH="${PW_PLUGINS_PATH}/portable/lib/lib64" "${PW_PLUGINS_PATH}/portable/bin/wrestool" \
            -x --output="${PORT_WINE_TMP_PATH}/tmp_img/" -t14 "$(readlink -f "${portwine_exe}")"
        fi
        cp "$(ls -S -1 "${PORT_WINE_TMP_PATH}/tmp_img/"*".ico" | head -n 1)" "${PORT_WINE_TMP_PATH}/tmp_img/${PORTPROTON_NAME}.ico"

        if command -v icotool &>/dev/null ; then
            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"
        else
            env LD_LIBRARY_PATH="${PW_PLUGINS_PATH}/portable/lib/lib64" "${PW_PLUGINS_PATH}/portable/bin/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"
        fi
        if [[ ! -f "$(ls -S -1 "${PORT_WINE_TMP_PATH}/tmp_img/"*".png" | grep "${PW_RESIZE_TO}x${PW_RESIZE_TO}")" ]] ; then
            if command -v icotool &>/dev/null ; then
                icotool -x --output="${PORT_WINE_TMP_PATH}/tmp_img/" "${PORT_WINE_TMP_PATH}/tmp_img/${PORTPROTON_NAME}.ico"
            else
                env LD_LIBRARY_PATH="${PW_PLUGINS_PATH}/portable/lib/lib64" "${PW_PLUGINS_PATH}/portable/bin/icotool" \
                -x --output="${PORT_WINE_TMP_PATH}/tmp_img/" "${PORT_WINE_TMP_PATH}/tmp_img/${PORTPROTON_NAME}.ico"
            fi
            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}"`" ]] \
    && command -v convert &>/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
}

pw_find_exe () {
    unset PW_FIND_TIME
    case "$1" in
        "news") PW_FIND_TIME="-cmin -180" ;;
    esac

    PW_EXCLUDE_EXE_FIND='(windows|explorer|anticheat|programdata|redist|setup|.ppdb|unin|error|crash|handler|install|/jre/|steam|uploader|eac|netframe)'
    PW_PATH_FOR_FIND="${PORT_WINE_PATH}/data/prefixes/"

    pw_start_progress_bar_block "Searching for .exe files... Please wait."
    find -P "${PW_PATH_FOR_FIND}" -type f -name "*.exe" ${PW_FIND_TIME} | grep -viE ${PW_EXCLUDE_EXE_FIND} | \
    awk -F"/prefixes/" '{print $2}' > "${PORT_WINE_TMP_PATH}/tmp_yad_find_exe"
    pw_stop_progress_bar

    unset FIND_TO_GUI
    while read line; do
        FIND_TO_GUI+="${line}%"
    done < "${PORT_WINE_TMP_PATH}/tmp_yad_find_exe"

    OrigIFS="$IFS" && IFS=%
    PW_SET_FIND_EXE="$("${pw_yad_v13_0}" --height="300" --width="1000" --list \
    --text-align=center --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --title "Create shortcut for..." \
    --text="\n${loc_gui_create_shortcut_for_exe}" --column="path to .exe file:" ${FIND_TO_GUI} 2>/dev/null)"
    YAD_STATUS="$?"
    print_var YAD_STATUS
    if [[ "$YAD_STATUS" == "1" || "$YAD_STATUS" == "252" ]] ; then
        if [[ -z "${PW_SET_FIND_EXE}" ]] ; then
            export SKIP_CHECK_UPDATES=1
            /usr/bin/env bash -c ${pw_full_command_line[*]} &
            print_info "Restarting..."
        fi
        exit 0
    fi
    IFS=$OrigIFS

    if [[ ! -z "${PW_SET_FIND_EXE}" ]] ; then
        portwine_exe="${PW_PATH_FOR_FIND}$(echo "${PW_SET_FIND_EXE}" | awk -F'|' '{print $1}')"
        portwine_create_shortcut silent
        export SKIP_CHECK_UPDATES=1
        /usr/bin/env bash -c ${pw_full_command_line[*]} &
        exit 0
    fi
}

pw_create_unique_exe () {
    BASEDIR_GAME="$(dirname "$portwine_exe")"
    if [[ -d "$BASEDIR_GAME" ]] ; then
        pushd "$BASEDIR_GAME"
        BASENAME_GAME_EXE="$(basename "$portwine_exe")"
        if [[ ! -z "$1" ]] ; then
            BASENAME_GAME="$(echo "$(basename "$1" .exe).exe")"
            ln -sf "$BASENAME_GAME_EXE" "$BASENAME_GAME"
            export portwine_exe="$BASEDIR_GAME/$BASENAME_GAME"
        elif [[ ! -z "$PORTWINE_CREATE_SHORTCUT_NAME" ]] ; then
            ln -sf "$BASENAME_GAME_EXE" "$PORTWINE_CREATE_SHORTCUT_NAME.exe"
            export portwine_exe="$BASEDIR_GAME/$PORTWINE_CREATE_SHORTCUT_NAME.exe"
        else
            print_warning "There are no arguments for creating a symbolic link! Skip it..."
        fi
        popd
    fi
}


start_portwine () {
    export WINEPREFIX="$(readlink -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}")"

    PROGPFX_URL="github.com/Castro-Fidel/PortWINE/releases/download/progpfx${PROGPFX_VER}/progpfx${PROGPFX_VER}.tar.xz"
    if [[ "${PW_PREFIX_NAME}" == "PROGRAMS" && ! -f "${WINEPREFIX}"/.progpfx ]] ; then
        print_info "Download and install PROGRAMS pfx..."
        if try_download "${PROGPFX_URL}" "${PORT_WINE_PATH}/data/tmp/progpfx.tar.xz" ; then
            unpack_tar_xz "${PORT_WINE_PATH}/data/tmp/progpfx.tar.xz" "${PORT_WINE_PATH}/data/prefixes/"
            try_remove_file "${PORT_WINE_PATH}/data/tmp/progpfx.tar.xz"
        else
            try_remove_file "${PORT_WINE_PATH}/data/tmp/progpfx.tar.xz"
            yad_error_download && exit 1
        fi
    fi

    DOTPFX_URL="github.com/Castro-Fidel/PortWINE/releases/download/dotpfx${DOTPFX_VER}/dotpfx${DOTPFX_VER}.tar.xz"
    if [[ "${PW_PREFIX_NAME}" == "DOTNET" ]] && [[ ! -f "${WINEPREFIX}"/.dotnet${DOTPFX_VER} ]] ; then
        print_info "Download and install DOTNET pfx..."
        if try_download "${DOTPFX_URL}" "${PORT_WINE_PATH}/data/tmp/dotpfx.tar.xz" ; then
            if unpack_tar_xz "${PORT_WINE_PATH}/data/tmp/dotpfx.tar.xz" "${PORT_WINE_PATH}/data/prefixes/"
            then touch "${WINEPREFIX}"/.dotnet${DOTPFX_VER}
            fi
            try_remove_file "${PORT_WINE_PATH}/data/tmp/dotpfx.tar.xz"
        else
            try_remove_file "${PORT_WINE_PATH}/data/tmp/dotpfx.tar.xz"
            yad_error_download && exit 1
        fi
    fi

    var_winedlloverride_update "${PW_MUST_WINEDLLOVERRIDES}"
    pw_list_install_dll_in_prefix
    if [[ "${PW_WINE_USE}" != "USE_SYSTEM_WINE" ]]
    then pw_check_and_download_wine "${PW_WINE_USE}"
    fi
    init_wine_ver
    pw_init_runtime

    check_variables VKD3D_DEBUG none
    check_variables DXVK_LOG_LEVEL none
    check_variables VK_LOADER_DEBUG none
    check_variables VKBASALT_LOG_LEVEL none
    check_variables DXVK_NVAPI_LOG_LEVEL none
    if [[ "${PW_LOG}" == 1 ]] ; then
        export WINEDEBUG="fixme-all,err+loaddll,err+dll,err+file,err+reg"
        export WINE_MONO_TRACE="E:System.NotImplementedException"
        export VKBASALT_LOG_LEVEL="error"
    else
        export WINEDEBUG="-all"
        unset WINE_MONO_TRACE
    fi

    pw_wineboot () {
            LIST_RM_WIN_DLL="winevulkan amd_ags_x64 ir50_32 atl100 ntdll \
libvkd3d-1 libvkd3d-shader-1 dxvk_config nvapi nvapi64 d3d12core d3d12 \
d3d11 d3d10 d3d10core d3d10_1 d3d9 d3d8 dxgi wined3d vulkan-1 shell32"
        for rm_win_dll in $LIST_RM_WIN_DLL ; do
            try_remove_file "${WINEPREFIX}/drive_c/windows/system32/${rm_win_dll}.dll"
            try_remove_file "${WINEPREFIX}/drive_c/windows/syswow64/${rm_win_dll}.dll"
        done

        print_info "Used wineboot $@ for prefix: ${PW_PREFIX_NAME}"
        ${pw_runtime} env GST_PLUGIN_SYSTEM_PATH_1_0="" LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" \
        WINEDEBUG="fixme-all,err+loaddll,err+dll,err+file,err+reg" \
        "${WINELOADER}" wineboot $@ &>>"${PORT_WINE_TMP_PATH}/update_pfx_log"
        wait_wineserver
        print_info "The prefix has been updated."
    }

    if [[ ! -d "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}"/drive_c/windows ]] \
    || [[ ! -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}"/userdef.reg ]] \
    || [[ ! -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}"/system.reg ]] \
    || [[ ! -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}"/user.reg ]]
    then
        pw_clear_pfx
        check_dirs_and_files_in_pfx
        if [[ "${PW_PREFIX_NAME}" == DEFAULT ]] ; then
            pw_update_pfx_cover_gui
            unpack_tar_xz "${PW_PLUGINS_PATH}/default_pfx.tar.xz" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/" silent
            pw_wineboot -r
        elif [[ "${PW_CHECK_AUTOINSTAL}" == 1 ]] \
        && [[ "${DISABLE_CP_DEFPFX}" != 1 ]] ; then
            pw_update_pfx_cover_gui
            unpack_tar_xz "${PW_PLUGINS_PATH}/default_pfx.tar.xz" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/" silent
            pw_wineboot -r
        elif [[ "${PW_CHECK_AUTOINSTAL}" == 1 ]] \
        && [[ "${DISABLE_CP_DEFPFX}" == 1 ]] ; then
            pw_update_pfx_cover_gui
            pw_wineboot -i
        elif yad_question "$loc_gui_dll_new_pfx ${PW_PREFIX_NAME}" ; then
            pw_update_pfx_cover_gui
            unpack_tar_xz "${PW_PLUGINS_PATH}/default_pfx.tar.xz" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/" silent
            pw_wineboot -r
        else
            pw_update_pfx_cover_gui
            pw_wineboot -i
        fi
    else
        check_dirs_and_files_in_pfx
        if [[ ! -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver" ]] \
        || ! grep "${PW_WINE_USE}" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver" &>/dev/null
        then
            pw_update_pfx_cover_gui
            # HOTFIX - update prefix for vkPlay
            if echo "$portwine_exe" | grep -i vkplay &>/dev/null
            then pw_kill_autostart GameCe 5 please & :
            fi
            pw_wineboot -r
        fi
    fi
    if grep 'xapofx1_' "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/user.reg" &>/dev/null ; then
        sed -i '/xapofx1_/d' "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/user.reg"
        sed -i '/x3daudio/d' "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/user.reg"
        sed -i '/xaudio2/d' "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/user.reg"
    fi
    echo "${PW_WINE_USE}" > "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver"

    # if [[ -f "$portwine_exe" ]] && [[ "${WARN_CYRILLIC_IN_PATH}" == 1 ]] ; then
    #     edit_db_from_gui WARN_CYRILLIC_IN_PATH
    #     unset WARN_CYRILLIC_IN_PATH
    # fi

    if [[ "$PW_USE_OBS_VKCAPTURE" == "1" ]] ; then
        export OBS_VKCAPTURE="1"
        export PW_USE_SYSTEM_VK_LAYERS="1"
        print_warning "System mangohud, vkBasalt, obs-vk capture and other applications using vulkan layers are forcibly used."
    fi

    if [[ "${PW_NO_ESYNC}" == 1 ]]
    then export WINEESYNC="0"
    else export WINEESYNC="1"
    fi

    if [[ "${PW_NO_FSYNC}" == 1 ]] ; then
        export WINEFSYNC="0"
        export WINEFSYNC_FUTEX2="0"
    else
        export WINEFSYNC="1"
        export WINEFSYNC_FUTEX2="1"
        export WINEFSYNC_SPINCOUNT=100
    fi

    if [[ "${PW_FORCE_LARGE_ADDRESS_AWARE}" == 1 ]]
    then export WINE_LARGE_ADDRESS_AWARE="1"
    else export WINE_LARGE_ADDRESS_AWARE="0"
    fi

    if [[ "${PW_OLD_GL_STRING}" == 1 ]] ; then
        export MESA_EXTENSION_MAX_YEAR="2003" #mesa override
        export __GL_ExtensionStringVersion="17700" #nvidia override
    fi

    if [[ "${PW_NO_WRITE_WATCH}" == 1 ]] ; then
        export WINE_DISABLE_WRITE_WATCH="1"
    fi

    if [[ "${PW_VULKAN_NO_ASYNC}" == 1 ]] ; then
        export RADV_DEBUG="llvm"
        var_vkd3d_config_update single_queue
    fi

    if [[ "${PW_USE_GAMESCOPE}" == 1 ]] && command -v gamescope &>/dev/null && ! check_gamescope_session ; then
        # Workaround for https://gitlab.freedesktop.org/mesa/mesa/-/issues/6029
        if [[ -d "/sys/module/i915" ]] ; then
            export INTEL_DEBUG="norbc"
        fi
        if [[ "${PW_GPU_USE}" != "disabled" ]] ; then
            PW_vendorID="$("$PW_VULKANINFO_PORTABLE" 2>/dev/null | grep -B3 "${PW_GPU_USE}" | grep vendorID | sort -u | awk -F'0x' '{print $2}')"
            PW_deviceID="$("$PW_VULKANINFO_PORTABLE" 2>/dev/null | grep -B3 "${PW_GPU_USE}" | grep deviceID | sort -u | awk -F'0x' '{print $2}')"
            PW_ID_VIDEO="--prefer-vk-device ${PW_vendorID}:${PW_deviceID}"
        else
            unset PW_ID_VIDEO
        fi
        export PW_RUN_GAMESCOPE="gamescope -o 30 ${PW_ID_VIDEO} ${GAMESCOPE_ARGS} --"
        export PW_WINE_FULLSCREEN_FSR="0"
        export vk_xwayland_wait_ready="false"
    else
        export PW_USE_GAMESCOPE="0"
        export PW_RUN_GAMESCOPE=""
    fi

    enabled_fake_nvidia_videocard ()
    {
        if [[ "${1}" == old ]] ; then
            sed -i /'dxgi.customDeviceDesc =/c # dxgi.customDeviceDesc =' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.customDeviceId =/c dxgi.customDeviceId = 222F' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.customVendorId =/c dxgi.customVendorId = 10de' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.hideAmdGpu =/c # dxgi.hideAmdGpu =' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.hideNvidiaGpu =/c # dxgi.hideNvidiaGpu =' "${DXVK_CONFIG_FILE}"
            unset WINE_HIDE_NVIDIA_GPU WINE_HIDE_AMD_GPU
            unset DXVK_NVAPI_DRIVER_VERSION DXVK_NVAPI_ALLOW_OTHER_DRIVERS
        elif [[ "${1}" == new ]] ; then
            sed -i /'dxgi.customDeviceDesc =/c dxgi.customDeviceDesc = "NVIDIA GeForce RTX 4090"' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.customDeviceId =/c dxgi.customDeviceId = 2684' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.customVendorId =/c dxgi.customVendorId = 10de' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.hideAmdGpu =/c dxgi.hideAmdGpu = True' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.hideNvidiaGpu =/c dxgi.hideNvidiaGpu = False' "${DXVK_CONFIG_FILE}"
            export WINE_HIDE_NVIDIA_GPU=0
            export WINE_HIDE_AMD_GPU=1
            export DXVK_NVAPI_DRIVER_VERSION=53713
            export DXVK_NVAPI_ALLOW_OTHER_DRIVERS=1
        elif [[ "${1}" == 0 ]] ; then
            sed -i /'dxgi.customDeviceDesc =/c # dxgi.customDeviceDesc =' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.customDeviceId =/c # dxgi.customDeviceId =' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.customVendorId =/c # dxgi.customVendorId =' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.hideAmdGpu =/c # dxgi.hideAmdGpu =' "${DXVK_CONFIG_FILE}"
            sed -i /'dxgi.hideNvidiaGpu =/c # dxgi.hideNvidiaGpu =' "${DXVK_CONFIG_FILE}"
            unset WINE_HIDE_NVIDIA_GPU WINE_HIDE_AMD_GPU
            unset DXVK_NVAPI_DRIVER_VERSION DXVK_NVAPI_ALLOW_OTHER_DRIVERS
        fi
    }

    for rm_dll in "nvml.dll" "nvngx.ini" "nvngx.dll" "_nvngx.dll" ; do
        try_remove_file "${WINEPREFIX}/drive_c/windows/syswow64/$rm_dll"
        try_remove_file "${WINEPREFIX}/drive_c/windows/system32/$rm_dll"
    done

    # TODO: LFX (wait new LFX v2)
    # if [[ "${PW_USE_LFX}" == 1 ]] ; then
    #     try_force_link_file "${PW_PLUGINS_PATH}/lfx/${PW_LFX_VER}/latencyflex_layer.so" "${WINEDIR}/lib64/wine/x86_64-unix/"
    #     try_force_link_file "${PW_PLUGINS_PATH}/lfx/${PW_LFX_VER}/latencyflex_layer.dll" "${WINEPREFIX}/drive_c/windows/system32/"
    #     try_force_link_file "${PW_PLUGINS_PATH}/lfx/${PW_LFX_VER}/latencyflex_wine.dll" "${WINEPREFIX}/drive_c/windows/system32/"
    #     enabled_fake_nvidia_videocard 1
    #     export LFX2=1
    # fi

    export DXVK_ENABLE_NVAPI=1
    if [[ "${PW_USE_FAKE_DLSS_3}" == 1 ]] ; then
        try_force_link_file "${PW_PLUGINS_PATH}/fake_dlss_3/${PW_FAKE_DLSS_3_VER}/nvngx.dll" "${WINEPREFIX}/drive_c/windows/system32/"
        try_force_link_file "${PW_PLUGINS_PATH}/fake_dlss/${PW_FAKE_DLSS_3_VER}/dlssg_to_fsr3_amd_is_better.dll" "${WINEPREFIX}/drive_c/windows/system32/"
        try_force_link_file "${PW_PLUGINS_PATH}/nvngx/_nvngx.dll" "${WINEPREFIX}/drive_c/windows/system32/"
        var_winedlloverride_update "nvapi,nvapi64,nvngx,_nvngx,dlssg_to_fsr3_amd_is_better=n;nvcuda=b"
        enabled_fake_nvidia_videocard new
        export WINEHAGS=1
    elif [[ "${PW_USE_FAKE_DLSS}" == 1 ]] && [[ -d "${PW_PLUGINS_PATH}/fake_dlss/${PW_FAKE_DLSS_VER}/" ]] ; then
        try_force_link_file "${PW_PLUGINS_PATH}/fake_dlss/${PW_FAKE_DLSS_VER}/nvngx.dll" "${WINEPREFIX}/drive_c/windows/system32/"
        try_force_link_file "${PW_PLUGINS_PATH}/fake_dlss/${PW_FAKE_DLSS_VER}/nvngx.ini" "${WINEPREFIX}/drive_c/windows/system32/"
        enabled_fake_nvidia_videocard old
        var_winedlloverride_update "nvapi,nvapi64,nvngx=n;_nvngx=;nvcuda=b"
    elif [[ "${PW_USE_NVAPI_AND_DLSS}" == 1 ]] ; then
        FIND_NVNGX="$(dirname $(find /usr/* -type f -name "nvngx.dll" 2>/dev/null | head -n 1 | awk '{print $1}'))"
        if [[ ! -z "$FIND_NVNGX" ]] ; then
            try_copy_file "${FIND_NVNGX}/nvngx.dll" "${WINEPREFIX}/drive_c/windows/system32/"
            try_copy_file "${FIND_NVNGX}/_nvngx.dll" "${WINEPREFIX}/drive_c/windows/system32/"
        else
            try_force_link_file "${PW_PLUGINS_PATH}/nvngx/nvngx.dll" "${WINEPREFIX}/drive_c/windows/system32/"
            try_force_link_file "${PW_PLUGINS_PATH}/nvngx/_nvngx.dll" "${WINEPREFIX}/drive_c/windows/system32/"
        fi
        enabled_fake_nvidia_videocard 0
        var_winedlloverride_update "nvngx,_nvngx,nvapi,nvapi64=n;nvcuda=b"
    else
        enabled_fake_nvidia_videocard 0
        export DXVK_ENABLE_NVAPI=0
        var_winedlloverride_update "nvngx,_nvngx="
    fi

    if [[ "${PW_USE_GALLIUM_ZINK}" == 1 ]]
    then export PW_VULKAN_USE=5
    fi

    if [[ "${PW_HEAP_DELAY_FREE}" == 1 ]]
    then export WINE_HEAP_DELAY_FREE="1"
    else export WINE_HEAP_DELAY_FREE="0"
    fi

    if [[ "${PW_WINE_ALLOW_XIM}" == 1 ]]
    then export WINE_ALLOW_XIM="1"
    else export WINE_ALLOW_XIM="0"
    fi

    if [[ "${PW_FIX_VIDEO_IN_GAME}" == 1 ]]
    then export WINE_DO_NOT_CREATE_DXGI_DEVICE_MANAGER="1"
    else export WINE_DO_NOT_CREATE_DXGI_DEVICE_MANAGER="0"
    fi

    [[ "${PW_MANGOHUD_USER_CONF}" == 1 ]] && unset MANGOHUD_CONFIG
    [[ "${PW_VKBASALT_USER_CONF}" == 1 ]] && unset PW_VKBASALT_EFFECTS PW_VKBASALT_FFX_CAS

    if [[ "${PW_USE_DXR11}" == 1 ]] \
    || [[ "${PW_USE_DXR10}" == 1 ]] \
    || [[ "${PW_USE_RAY_TRACING}" == 1 ]]
    then
        export VKD3D_FEATURE_LEVEL="12_1"
        var_vkd3d_config_update dxr
        var_radv_perftest_config_update rt
    else
        var_vkd3d_config_update nodxr
    fi

    if [[ "${PW_GPU_USE}" != "disabled" ]] ; then
        export DXVK_FILTER_DEVICE_NAME="${PW_GPU_USE}"
        export VKD3D_FILTER_DEVICE_NAME="${PW_GPU_USE}"
        if echo "${PW_GPU_USE}" | grep -i nvidia &>/dev/null ; then
            if [[ -f "/usr/share/vulkan/icd.d/nvidia_icd.json" ]] ; then
                export VK_ICD_FILENAMES="/usr/share/vulkan/icd.d/nvidia_icd.json"
            fi
        fi
    fi

    case "$PW_FORCE_USE_VSYNC" in  # 0-FORCE_OFF, 1-FORCE_ON, 2-BY_DEFAULT
        0)
            export  vblank_mode=0
            export __GL_SYNC_TO_VBLANK=0
            ;;
        1)
            export vblank_mode=1
            export __GL_SYNC_TO_VBLANK=1
            ;;
        *)
            unset vblank_mode __GL_SYNC_TO_VBLANK
            ;;
    esac

    export int_xneur=0
    if [[ ! -z "`pgrep xneur`" ]]; then
        killall xneur
        export int_xneur=1
    fi

    if check_gamescope_session ; then
        export PW_GAMEMODERUN_SLR=""
    elif [[ "$PW_USE_GAMEMODE" = "1" ]] ; then
        if command -v gamemoded &>/dev/null ; then
            export GAMEMODERUN=1
            PW_GAMEMODERUN_SLR="gamemoderun"
            systemctl enable --now --user gamemoded &>/dev/null
            print_info "Gamemod will be launched."
        elif check_flatpak ; then
            export GAMEMODERUN=1
            PW_GAMEMODERUN_SLR="gamemoderun"
            print_info "Gamemod will be launched."
        elif [[ "$PW_USE_RUNTIME" == 1 ]] ; then
            export GAMEMODERUN=1
            if ! pidof gamemoded &>/dev/null ; then
                GAMEMODEAUTO_NAME="libgamemodeauto.so.0"
                if [[ ! -z "${PW_LD_PRELOAD}" ]]
                then export PW_LD_PRELOAD="${PW_LD_PRELOAD}:${GAMEMODEAUTO_NAME}"
                else export PW_LD_PRELOAD="${GAMEMODEAUTO_NAME}"
                fi

                env LD_LIBRARY_PATH="${PW_PLUGINS_PATH}/portable/lib/lib64:${PW_PLUGINS_PATH}/portable/lib/lib32" \
                "${PW_PLUGINS_PATH}/portable/bin/gamemoded" &>/dev/null &

                print_info "Gamemod will be launched."
                sleep 0.1
            fi
        else
            export GAMEMODERUN=0
            export PW_GAMEMODERUN_SLR=""
        fi
    else
        export GAMEMODERUN=0
        export PW_GAMEMODERUN_SLR=""
        print_info "Gamemod is not installed or disabled in vars script or db file: PW_USE_GAMEMODE=$PW_USE_GAMEMODE"
    fi
    pw_other_fixes

    #enabled BattleEye_Runtime and EasyAntiCheat_Runtime
    if [[ "${PW_USE_EAC_AND_BE}" == 1 ]] ; then
        export PROTON_BATTLEYE_RUNTIME="${PW_PLUGINS_PATH}/BattlEye_Runtime"
        export PROTON_EAC_RUNTIME="${PW_PLUGINS_PATH}/EasyAntiCheat_Runtime"
        var_winedlloverride_update "beclient,beclient_x64=b,n"
    else
        unset PROTON_BATTLEYE_RUNTIME PROTON_EAC_RUNTIME
    fi

    if [[ "${PW_REDUCE_PULSE_LATENCY}" == 1 ]] ; then
        export PULSE_LATENCY_MSEC=60
        # export PIPEWIRE_LATENCY=128/48000
    else
        unset PULSE_LATENCY_MSEC
    fi

    if [[ "$PW_USE_US_LAYOUT" == "1" ]] \
    && [[ "${XDG_SESSION_TYPE}" != "wayland" ]] \
    && command -v setxkbmap &>/dev/null
    then
        setxkbmap -model pc101 us -print | xkbcomp - $DISPLAY &>/dev/null
    else
        export PW_USE_US_LAYOUT="0"
    fi

    D3D_EXTRAS_LIBS="d3dcompiler_33 d3dcompiler_34 d3dcompiler_35 d3dcompiler_36 d3dcompiler_37
    d3dcompiler_38 d3dcompiler_39 d3dcompiler_40 d3dcompiler_41 d3dcompiler_42 d3dcompiler_43 d3dcompiler_46
    d3dcompiler_47 d3dx10_33 d3dx10_34 d3dx10_35 d3dx10_36 d3dx10_37 d3dx10_38 d3dx10_39 d3dx10_40 d3dx10_41
    d3dx10_42 d3dx10_43 d3dx10 d3dx11_42 d3dx11_43 d3dx9_24 d3dx9_25 d3dx9_26 d3dx9_27 d3dx9_28 d3dx9_29 d3dx9_30
    d3dx9_31 d3dx9_32 d3dx9_33 d3dx9_34 d3dx9_35 d3dx9_36 d3dx9_37 d3dx9_38 d3dx9_39 d3dx9_40 d3dx9_41 d3dx9_42 d3dx9_43"
    if [[ "${PW_USE_D3D_EXTRAS}" == 1 ]] ; then
        if [[ ! -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ]] \
        || [[ -z "`grep d3dx9 "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"`" ]]
        then
            echo "d3dx9" >> "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
        fi
        # try link d3d extras libs
        PATH_TO_D3DEXTRAS="${PW_PLUGINS_PATH}/d3d_extras"
        for d3d_extras_from_plugins in $D3D_EXTRAS_LIBS ; do
            try_force_link_file "${PATH_TO_D3DEXTRAS}/x64/${d3d_extras_from_plugins}.dll" "${WINEPREFIX}/drive_c/windows/system32/"
            try_force_link_file "${PATH_TO_D3DEXTRAS}/x32/${d3d_extras_from_plugins}.dll" "${WINEPREFIX}/drive_c/windows/syswow64/"
            var_winedlloverride_update "${d3d_extras_from_plugins}=n"
            if [[ -z "`grep "${d3d_extras_from_plugins}" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"`" ]] ; then
                echo "${d3d_extras_from_plugins}" >> "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
            fi
        done
    else
        for d3d_extras_from_plugins in $D3D_EXTRAS_LIBS ; do
            try_force_link_file "${WINEDIR}/lib/wine/i386-windows/${d3d_extras_from_plugins}.dll" "${WINEPREFIX}/drive_c/windows/syswow64/"
            try_force_link_file "${WINEDIR}/lib64/wine/x86_64-windows/${d3d_extras_from_plugins}.dll" "${WINEPREFIX}/drive_c/windows/system32/"
        done
    fi

    # fix physx
    PHYSX_PATH="${WINEPREFIX}/drive_c/Program Files (x86)/NVIDIA Corporation/PhysX/Common"
    for physx_dll in PhysXDevice PhysXLoader PhysXUpdateLoader ; do
        try_force_link_file "${PHYSX_PATH}/${physx_dll}.dll" "${WINEPREFIX}/drive_c/windows/syswow64/"
        try_force_link_file "${PHYSX_PATH}/${physx_dll}64.dll" "${WINEPREFIX}/drive_c/windows/system32/"
    done
    try_force_link_file "${PHYSX_PATH}/cudart32_65.dll" "${WINEPREFIX}/drive_c/windows/syswow64/"
    try_force_link_file "${PHYSX_PATH}/cudart64_65.dll" "${WINEPREFIX}/drive_c/windows/system32/"

    create_new_dir "${PW_VULKAN_DIR}/opengl"
    PATH_TO_DXVK_FILES="${PW_VULKAN_DIR}/opengl"
    PATH_TO_VKD3D_FILES="${PW_VULKAN_DIR}/opengl"

    if [[ "${PW_VULKAN_USE}" == "0" ]] ; then
        print_info "Use OpenGL"
        export GL_YIELD="NOTHING"
        export mesa_glthread=true
        export WINE_D3D_CONFIG='renderer=gl'
    elif [[ "${PW_VULKAN_USE}" == "5" ]] ; then
        print_info "Use OpenGL Zink"
        export GL_YIELD="NOTHING"
        export mesa_glthread=true
        export WINE_D3D_CONFIG='renderer=gl'
        export  __GLX_VENDOR_LIBRARY_NAME=mesa
        export MESA_LOADER_DRIVER_OVERRIDE=zink
        export GALLIUM_DRIVER=zink
        if [[ "${XDG_SESSION_TYPE}" != "wayland" ]] || [[ "${PW_USE_GAMESCOPE}" != 1 ]] ; then
            export LIBGL_KOPPER_DRI2=1
        fi
    elif [[ "${PW_VULKAN_USE}" == "3" ]] ; then
        print_info "Use GALLIUM-NINE (Native DX9 on MESA drivers)"
        export PW_GALLIUM_NINE_PATH="${PW_PLUGINS_PATH}/gallium_nine_v.${PW_GALLIUM_NINE_VER}"
        try_force_link_file "${PW_GALLIUM_NINE_PATH}/lib32/d3d9-nine.dll.so" "${WINEPREFIX}/drive_c/windows/syswow64/d3d9.dll"
        try_force_link_file "${PW_GALLIUM_NINE_PATH}/lib64/d3d9-nine.dll.so" "${WINEPREFIX}/drive_c/windows/system32/d3d9.dll"
        var_winedlloverride_update "d3d9=n;wined3d=b;dxvk_config,vulkan-1,winevulkan="
        unset FIND_D3D_MODULE D3D_MODULE_PATH
        FIND_D3D_MODULE=`dirname $(find /usr/ -maxdepth 4 -type f -name "d3dadapter9.so.*") 2>/dev/null`
        if [[ ! -z "$FIND_D3D_MODULE" ]] ; then
            old_IFS=$IFS
            IFS=$'\n'
            for D3D_MP in $FIND_D3D_MODULE ; do
                if [[ ! -z "$D3D_MODULE_PATH" ]]
                then export D3D_MODULE_PATH="$D3D_MODULE_PATH:/run/host${D3D_MP}"
                else export D3D_MODULE_PATH="/run/host${D3D_MP}"
                fi
            done
            IFS=$old_IFS
            print_info "D3D_MODULE_PATH=${D3D_MODULE_PATH}"
        else
            pw_stop_progress_bar
            yad_error "d3dadapter9.so.1.0.0 - ${loc_find_d3dadapter9_error}"
            stop_portwine
        fi
        export mesa_glthread=true
        export ENABLE_VKBASALT=0
        export PW_MANGOHUD=0
        export WINE_FULLSCREEN_FSR=0
    elif [[ "${PW_VULKAN_USE}" == "4" ]] ; then
        print_info "Use DAMAVAND (DirectX to wined3d vulkan)"
        export WINE_D3D_CONFIG='renderer=vulkan'
    else
        print_info "Use VKD3D-PROTON, DXVK and D8VK (DirectX 8-12 to vulkan)"
        if [[ "${PW_USE_WINE_DXGI}" == 1 ]] ; then
            export CP_DXVK_FILES="d3d11 d3d10core d3d9 dxvk_config" # openvr_api_dxvk
            var_winedlloverride_update dxgi=b
        elif [[ "${USE_ALL_DXVK_DLLS}" == 1 ]] ; then
            export CP_DXVK_FILES="d3d11 d3d10core d3d10_1 d3d10 d3d9 dxgi dxvk_config" # openvr_api_dxvk
        else
            export CP_DXVK_FILES="d3d11 d3d10core d3d9 dxgi dxvk_config" # openvr_api_dxvk
        fi
        check_variables VKD3D_FEATURE_LEVEL "12_0"
        if [[ "${PW_VULKAN_USE}" == "1" ]] ; then
            export PATH_TO_DXVK_FILES="${PW_VULKAN_DIR}/dxvk-${DXVK_STABLE_VER}"
            export PATH_TO_VKD3D_FILES="${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_STABLE_VER}"
            print_info "DXVK v.${DXVK_STABLE_VER} in use"
            print_info "VKD3D-PROTON v.${VKD3D_STABLE_VER} in use"
        elif [[ "${PW_VULKAN_USE}" == "2" ]] ; then
            export PATH_TO_DXVK_FILES="${PW_VULKAN_DIR}/dxvk-${DXVK_GIT_VER}"
            export PATH_TO_VKD3D_FILES="${PW_VULKAN_DIR}/vkd3d-proton-${VKD3D_GIT_VER}"
            print_info "DXVK v.${DXVK_GIT_VER} in use"
            print_info "VKD3D-PROTON v.${VKD3D_GIT_VER} in use"
        fi
        PATH_TO_D8VK_FILES="${PW_VULKAN_DIR}/d8vk-${D8VK_VER}"
        print_info "D8VK v.${D8VK_VER} in use"

        print_info "Try link native DXVK files..."
        for wine_dxvk_dll in ${CP_DXVK_FILES} ; do
            if [[ -f "${PATH_TO_DXVK_FILES}/x64/${wine_dxvk_dll}.dll"  ]] ; then
                try_force_link_file "${PATH_TO_DXVK_FILES}/x32/${wine_dxvk_dll}.dll" "${WINEPREFIX}/drive_c/windows/syswow64/"
                try_force_link_file "${PATH_TO_DXVK_FILES}/x64/${wine_dxvk_dll}.dll" "${WINEPREFIX}/drive_c/windows/system32/"
                var_winedlloverride_update "${wine_dxvk_dll}=n"
            fi
        done

        try_force_link_file "${PATH_TO_DXVK_FILES}/x32/nvapi.dll" "${WINEPREFIX}/drive_c/windows/syswow64/" || \
        try_force_link_file "${PW_PLUGINS_PATH}/nvapi/x32/nvapi.dll" "${WINEPREFIX}/drive_c/windows/syswow64/"

        try_force_link_file "${PATH_TO_DXVK_FILES}/x64/nvapi64.dll" "${WINEPREFIX}/drive_c/windows/system32/" || \
        try_force_link_file "${PW_PLUGINS_PATH}/nvapi/x64/nvapi64.dll" "${WINEPREFIX}/drive_c/windows/system32/"

        print_info "Try link native VKD3D files..."
        for wine_vkd3d_dll in d3d12 d3d12core libvkd3d-1 libvkd3d-shader-1; do
            if [[ -f "${PATH_TO_VKD3D_FILES}/x64/${wine_vkd3d_dll}.dll" ]] ; then
                try_force_link_file "${PATH_TO_VKD3D_FILES}/x86/${wine_vkd3d_dll}.dll" "${WINEPREFIX}/drive_c/windows/syswow64/"
                try_force_link_file "${PATH_TO_VKD3D_FILES}/x64/${wine_vkd3d_dll}.dll" "${WINEPREFIX}/drive_c/windows/system32/"
                var_winedlloverride_update "${wine_vkd3d_dll}=n"
            fi
        done

        print_info "Try link native D8VK file..."
        try_force_link_file "${PATH_TO_D8VK_FILES}/x32/d3d8.dll" "${WINEPREFIX}/drive_c/windows/syswow64/"
        try_force_link_file "${PATH_TO_D8VK_FILES}/x64/d3d8.dll" "${WINEPREFIX}/drive_c/windows/system32/"
        var_winedlloverride_update d3d8=n
    fi

    if [[ ! -d "${WINEPREFIX}/drive_c/vrclient/bin" ]] ; then
        create_new_dir "${WINEPREFIX}/drive_c/vrclient/bin"
        try_force_link_file "${WINEDIR}"/lib/wine/i386-windows/vrclient.dll "${WINEPREFIX}/drive_c/vrclient/bin/"
        try_force_link_file "${WINEDIR}"/lib64/wine/x86_64-windows/vrclient_x64.dll "${WINEPREFIX}/drive_c/vrclient/bin/"
    fi

    if [[ "${PW_USE_SHADER_CACHE}" == 1 ]] ; then
        create_new_dir "${PATH_TO_DXVK_FILES}/gl_shader_cache"
        export __GL_SHADER_DISK_CACHE=1
        export __GL_SHADER_DISK_CACHE_PATH="${PATH_TO_DXVK_FILES}/gl_shader_cache"
        export __GL_SHADER_DISK_CACHE_SIZE=50000000000
        export __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1
        create_new_dir "${PATH_TO_DXVK_FILES}/dxvk_cache"
        export DXVK_STATE_CACHE_PATH="${PATH_TO_DXVK_FILES}"/dxvk_cache
        export DXVK_STATE_CACHE=1
        create_new_dir "${PATH_TO_VKD3D_FILES}/vkd3d_cache"
        export VKD3D_SHADER_CACHE_PATH="${PATH_TO_VKD3D_FILES}/vkd3d_cache"
    else
        export __GL_SHADER_DISK_CACHE=0
        export DXVK_STATE_CACHE=0
        export VKD3D_SHADER_CACHE_PATH=0
        export RADV_DEBUG=nocache
    fi

    if [[ "${PW_WINE_FULLSCREEN_FSR}" == 1 ]] || [[ "${WINE_FULLSCREEN_FSR}" == 1 ]] ; then
        export WINE_FULLSCREEN_FSR=1
        export WINE_FULLSCREEN_FSR_STRENGTH=2
        export WINE_FULLSCREEN_INTEGER_SCALING=0
    else
        export WINE_FULLSCREEN_FSR=0
        unset WINE_FULLSCREEN_FAKE_CURRENT_RES WINE_FULLSCREEN_FSR_STRENGTH WINE_FULLSCREEN_INTEGER_SCALING
    fi

    if [[ "${PW_WINE_CPU_TOPOLOGY}" != "disabled" ]] ; then
        export WINE_CPU_TOPOLOGY="${PW_WINE_CPU_TOPOLOGY}"
    fi

    #run_winetricks_from_db
    if [[ ! -z "${PW_MUST_HAVE_DLL}" ]]
    then export PW_DLL_INSTALL="`echo "${PW_MUST_HAVE_DLL} ${PW_DLL_INSTALL}" | awk '{ for(i=1;i<=NF;i++){a[$i]++} }END{ for(i in a){printf("%s ",i)} }' `"
    fi

    if [[ ! -z "${PW_DLL_INSTALL}" ]] ; then
        export PW_DLL_NEED_INSTALL=""
        export USE_WT_FROM_DB=0
        if [ ! -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ] ; then
            touch "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
        fi
        for need_install_dll_to_pfx in ${PW_DLL_INSTALL} ; do
            if [[ "${need_install_dll_to_pfx}" == vcrun201[5-9] ]] \
            || [[ "${need_install_dll_to_pfx}" == vcrun2022 ]] ; then
                need_install_dll_to_pfx="vcrun2022"
                sed -i '/vcrun2015/d' "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
                sed -i '/vcrun2017/d' "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
                sed -i '/vcrun2019/d' "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
            fi
            grep "${need_install_dll_to_pfx}" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" &>/dev/null
            if [[ "$?" == "1" ]] ; then
                if [[ -z "${PW_DLL_NEED_INSTALL}" ]]
                then export PW_DLL_NEED_INSTALL="${need_install_dll_to_pfx}"
                else export PW_DLL_NEED_INSTALL="${need_install_dll_to_pfx} ${PW_DLL_NEED_INSTALL}"
                fi
                export USE_WT_FROM_DB=1
            fi
        done
        if [[ "${USE_WT_FROM_DB}" == "1" ]] ; then
            pw_update_pfx_cover_gui
            update_winetricks
            echo "START WINETRICKS..." >> "${PORT_WINE_TMP_PATH}/update_pfx_log"
            echo "Try to install DLL in prefix: ${PW_DLL_NEED_INSTALL}" >> "${PORT_WINE_TMP_PATH}/update_pfx_log"
            print_info "Try to install DLL in prefix: ${PW_DLL_NEED_INSTALL}"
            ${pw_runtime} env PATH="${PATH}" LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" GST_PLUGIN_SYSTEM_PATH_1_0="" \
            "${PORT_WINE_TMP_PATH}/winetricks" -q -r -f ${PW_DLL_NEED_INSTALL} | tee -a "${PORT_WINE_TMP_PATH}/update_pfx_log"
            wait_wineserver
            kill_portwine
        fi
    fi

    if [[ -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/system.reg" ]] \
    && [[ -z `grep "Windows $PW_WINDOWS_VER" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/system.reg"` ]]
    then
        if [[ ! -z "${PW_WINDOWS_VER}" && `echo "$PW_WINDOWS_VER" | sed 's/.*/\L&/'` == "xp" ]] ; then
            export PW_WINDOWS_VER="xp64"
        fi
        ${pw_runtime} env PATH="${PATH}" LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" GST_PLUGIN_SYSTEM_PATH_1_0="" \
        "${WINELOADER}" winecfg -v `echo "win${PW_WINDOWS_VER}" | sed 's/.*/\L&/'`
        wait_wineserver
        kill_portwine
        echo "Set to win${PW_WINDOWS_VER}"
    fi

    if [[ "${portwine_exe}" == *-Shipping.exe ]] ; then
        echo "Disable EAC"
        [[ -z "${LAUNCH_PARAMETERS}" ]] && export LAUNCH_PARAMETERS+=" -eac-nop-loaded "
    fi
    pw_stop_progress_bar &&
    if ! check_start_from_steam ; then
        pw_tray_icon
        sleep 0.5
        if [[ "${PW_CHECK_AUTOINSTAL}" != "1" ]] ; then
            pw_start_progress_bar_cover "${PW_GUI_ICON_PATH}/covers/loading_${update_loc}.gif"
        fi
    fi
    add_in_start_portwine

    if [[ -f "${PATH_TO_GAME}/dxvk.conf" ]] ; then
        export DXVK_CONFIG_FILE="${PATH_TO_GAME}/dxvk.conf"
    fi

    if [[ "${PW_DISABLE_COMPOSITING}" == "1" ]] \
    && ! check_gamescope_session
    then
        if [[ "${DESKTOP_SESSION}" =~ "plasma" ]] ; then
            qdbus org.kde.KWin /Compositor suspend
        elif [[ "${DESKTOP_SESSION}" =~ "mate" ]] ; then
            gsettings set org.mate.Marco.general compositing-manager false
        elif [[ "${DESKTOP_SESSION}" =~ "xfce" ]] ; then
            xfconf-query -c xfwm4 -p /general/use_compositing -s false
        elif [[ "${DESKTOP_SESSION}" =~ "cinnamon" ]] ; then
            gsettings set org.cinnamon.muffin unredirect-fullscreen-windows true
        fi
    fi

    pw_mangohud_check
    pw_vkbasalt_check
}

pw_run () {
    unset GDK_BACKEND
    if [[ ! -z "${PATH_TO_GAME}" ]] && [[ -d "${PATH_TO_GAME}" ]] ; then
        cd "${PATH_TO_GAME}"
    elif [[ -f "$portwine_exe" ]] ; then
        export PATH_TO_GAME="$( cd "$( dirname "${portwine_exe}" )" >/dev/null 2>&1 && pwd )"
        cd "${PATH_TO_GAME}"
    else
        cd "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c"
    fi
    PW_LOG_TO_FILE="${PORT_WINE_PATH}/${portname}.log"
    print_var "WINEDIR" "WINEPREFIX" "WINEDLLOVERRIDES" "PATH_TO_GAME" "PW_WINE_USE" "PW_VULKAN_USE" "VULKAN_DRIVER_NAME"
    print_var "VULKAN_API_DRIVER_VERSION" "VKD3D_CONFIG" "PW_LD_LIBRARY_PATH" "PATH" "WINEESYNC" "WINEFSYNC" "WINEFSYNC_FUTEX2"
    print_var "WINEDLLPATH" "WINE_CPU_TOPOLOGY" "PW_RUN_GAMESCOPE" "LD_LIBRARY_PATH"
    kill -s SIGUSR1 "$PW_YAD_PID_PFX_COVER_UI" &>/dev/null
    if [[ "$PW_USE_RUNTIME" == 1 ]] \
    && [[ "$PW_WINE_USE" != "USE_SYSTEM_WINE" ]]
    then
        if [[ "${PW_LOG}" == 1 ]] ; then
            if check_start_from_steam ; then
                for VAR_LOGGER in PW_WINE_USE WINEDIR WINEDLLPATH WINEPREFIX PATH_TO_GAME PW_VULKAN_USE PW_LD_LIBRARY_PATH LD_LIBRARY_PATH PATH \
                                VKD3D_CONFIG WINEESYNC WINEFSYNC WINEFSYNC_FUTEX2 WINE_CPU_TOPOLOGY DESKTOP_SESSION
                do
                    echo "${VAR_LOGGER}=${!VAR_LOGGER}" >> "${PW_LOG_TO_FILE}"
                done
            fi
            echo "WINEDLLOVERRIDES=${WINEDLLOVERRIDES}" >> "${PW_LOG_TO_FILE}"
            echo "------------------------------------" >> "${PW_LOG_TO_FILE}"
            [[ -f "${PORT_WINE_TMP_PATH}/update_pfx_log" ]] && cat "${PORT_WINE_TMP_PATH}/update_pfx_log" >> "${PW_LOG_TO_FILE}"
            echo "-" >> "${PW_LOG_TO_FILE}"
            echo "Log WINE:" >> "${PW_LOG_TO_FILE}"
            echo ""
            print_info "Log from RUNTIME and WINE:"
            ${PW_RUN_GAMESCOPE} \
            ${pw_runtime} \
            env PATH="${PATH}" \
            LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" \
            LD_PRELOAD="${PW_LD_PRELOAD}" \
            VK_LAYER_PATH="${PW_VK_LAYER_PATH}" \
            VK_INSTANCE_LAYERS=${PW_VK_INSTANCE_LAYERS} \
            ${PW_GAMEMODERUN_SLR} \
            ${PW_MANGOHUD_SLR} \
            "${WINELOADER}" "$@" ${LAUNCH_PARAMETERS[@]} &>>"${PW_LOG_TO_FILE}"
        else
            if [[ "$PW_USE_TERMINAL" == 1 ]] \
            && [[ "$PW_USE_RUNTIME" == 1 ]]
            then
                export PW_ADD_TO_ARGS_IN_RUNTIME="--xterm"
                pw_init_runtime
            fi
            echo ""
            echo "Log WINE:" > "${PW_LOG_TO_FILE}"
            ${PW_RUN_GAMESCOPE} \
            ${pw_runtime} \
            env PATH="${PATH}" \
            LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" \
            LD_PRELOAD="${PW_LD_PRELOAD}" \
            VK_LAYER_PATH="${PW_VK_LAYER_PATH}" \
            VK_INSTANCE_LAYERS="${PW_VK_INSTANCE_LAYERS}" \
            ${PW_GAMEMODERUN_SLR} \
            ${PW_MANGOHUD_SLR} \
            "${WINELOADER}" "$@" ${LAUNCH_PARAMETERS[@]} &>>"${PW_LOG_TO_FILE}"
            print_info "Update prefix log:"
            [[ -f "${PORT_WINE_TMP_PATH}/update_pfx_log" ]] && cat "${PORT_WINE_TMP_PATH}/update_pfx_log"
            echo
            print_info "Log from RUNTIME and WINE:"
            cat "${PW_LOG_TO_FILE}"
            echo
        fi
    else
        if [[ "${PW_LOG}" == 1 ]] ; then
            if check_start_from_steam ; then
                for VAR_LOGGER in PW_WINE_USE WINEDIR WINEDLLPATH WINEPREFIX PATH_TO_GAME PW_VULKAN_USE PW_LD_LIBRARY_PATH LD_LIBRARY_PATH PATH \
                                VKD3D_CONFIG WINEESYNC WINEFSYNC WINEFSYNC_FUTEX2 WINE_CPU_TOPOLOGY DESKTOP_SESSION
                do
                    echo "${VAR_LOGGER}=${!VAR_LOGGER}" >> "${PW_LOG_TO_FILE}"
                done
            fi
            echo "WINEDLLOVERRIDES=${WINEDLLOVERRIDES}" >> "${PW_LOG_TO_FILE}"
            echo "------------------------------------" >> "${PW_LOG_TO_FILE}"
            [[ -f "${PORT_WINE_TMP_PATH}/update_pfx_log" ]] && cat "${PORT_WINE_TMP_PATH}/update_pfx_log" >> "${PW_LOG_TO_FILE}"
            echo "-" >> "${PW_LOG_TO_FILE}"
            echo "Log WINE:" >> "${PW_LOG_TO_FILE}"
            echo ""
            print_info "Log WINE:"
            env FAKE_VAR= \
            ${PW_RUN_GAMESCOPE} \
            ${PW_GAMEMODERUN_SLR} \
            ${PW_MANGOHUD_SLR} \
            "${WINELOADER}" "$@" ${LAUNCH_PARAMETERS[@]} &>>"${PW_LOG_TO_FILE}"
            wait_wineserver
        else
            print_info "Update prefix log:"
            [[ -f "${PORT_WINE_TMP_PATH}/update_pfx_log" ]] && cat "${PORT_WINE_TMP_PATH}/update_pfx_log"
            echo ""
            echo "Log WINE:" > "${PW_LOG_TO_FILE}"
            print_info "Log WINE:"
            env FAKE_VAR= \
            ${PW_RUN_GAMESCOPE} \
            ${PW_GAMEMODERUN_SLR} \
            ${PW_MANGOHUD_SLR} \
            "${WINELOADER}" "$@" ${LAUNCH_PARAMETERS[@]}
            wait_wineserver

            # ${PW_RUN_GAMESCOPE} \ !!!
        fi
    fi
}
export -f pw_run

portwine_launch () {
    start_portwine
    PORTWINE_MSI=$(basename "${portwine_exe}" | grep .msi)
    PORTWINE_BAT=$(basename "${portwine_exe}" | grep .bat)
    if [[ ! -z "${PW_VIRTUAL_DESKTOP}" && "${PW_VIRTUAL_DESKTOP}" == "1" ]] ; then
        pw_run explorer "/desktop=PortProton,${PW_SCREEN_RESOLUTION}" ${WINE_WIN_START} "$portwine_exe"
    elif [ ! -z "${PORTWINE_MSI}" ]; then
        pw_run msiexec /i "$portwine_exe"
    elif [[ ! -z "${PORTWINE_BAT}" || -n "${portwine_exe}" ]] ; then
        pw_run ${WINE_WIN_START} "$portwine_exe"
    else
        pw_run winefile
    fi
}


pw_winecfg () {
    start_portwine
    export GST_PLUGIN_SYSTEM_PATH_1_0=""
    pw_run winecfg
}

pw_winefile () {
    start_portwine
    pw_run winefile
}

pw_winecmd () {
    export PW_USE_TERMINAL=1
    start_portwine
    cd "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c"
    ${pw_runtime} env LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" "${PW_PLUGINS_PATH}/portable/bin/xterm" -e "${WINELOADER}" cmd
    stop_portwine
}

pw_winereg () {
    start_portwine
    export GST_PLUGIN_SYSTEM_PATH_1_0=""
    pw_run regedit
}

pw_start_cont_xterm () {
    cd "$HOME"
    unset PW_SANDBOX_HOME_PATH
    pw_init_runtime
    ${pw_runtime} \
    env PATH="${PATH}" \
    LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" \
    LD_PRELOAD="${PW_LD_PRELOAD}" \
    VK_LAYER_PATH="${PW_VK_LAYER_PATH}" \
    VK_INSTANCE_LAYERS="${PW_VK_INSTANCE_LAYERS}" \
    ${PW_GAMEMODERUN_SLR} \
    ${PW_MANGOHUD_SLR} \
    "${PW_PLUGINS_PATH}/portable/bin/xterm"
}

#!/usr/bin/env bash
# Author: Castro-Fidel (linux-gaming.ru)
########################################################################
yad_info () {
    print_info "$@"
    if [[ ! -f "${pw_yad_v13_0}" ]] ; then
        local pw_yad_v13_0="yad"
        command -v "${pw_yad_v13_0}" &>/dev/null || fatal "yad not found"
    fi
    "${pw_yad_v13_0}" --no-wrap --text "$@" --width=400 --height=50 --borders=15 --title "INFO" \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --image="$PW_GUI_ICON_PATH/info.png" \
    --center --text-align=center \
    --button="OK"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png" 2>/dev/null
}
export -f yad_info

yad_error () {
    print_error "$@"
    if [[ ! -f "${pw_yad_v13_0}" ]] ; then
        local pw_yad_v13_0="yad"
        command -v "${pw_yad_v13_0}" &>/dev/null || fatal "yad not found"
    fi
    "${pw_yad_v13_0}" --no-wrap --text "$@" --width=400 --borders=15 --title "ERROR" \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --image="$PW_GUI_ICON_PATH/error.png" \
    --center --text-align=center \
    --button="EXIT"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png" 2>/dev/null
}
export -f yad_error

yad_error_download () {
    if [[ ! -f "${pw_yad_v13_0}" ]] ; then
        local pw_yad_v13_0="yad"
        command -v "${pw_yad_v13_0}" &>/dev/null || fatal "yad not found"
    fi
    "${pw_yad_v13_0}" --text "$loc_gui_error_download" --width=400 --borders=15 --title "$loc_gui_error" \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --image="$PW_GUI_ICON_PATH/download.png" \
    --no-wrap --center --text-align=center\
    --button="SKIP"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":1 \
    --button="REPEAT"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":0 2>/dev/null
    [[ "$?" != 0 ]] && return 1 || return 0
}

yad_question () {
    if [[ ! -f "${pw_yad_v13_0}" ]] ; then
        local pw_yad_v13_0="yad"
        command -v "${pw_yad_v13_0}" &>/dev/null || fatal "yad not found"
    fi
    "${pw_yad_v13_0}" --text "${1}" --width=400 --borders=15 --title "${inst_set}." \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --image="$PW_GUI_ICON_PATH/question.png" \
    --no-wrap --center --text-align=center \
    --button="$loc_cancel"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":1 \
    --button="OK"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":0 2>/dev/null
    [[ "$?" != 0 ]] && return 1 || return 0
}

pw_start_progress_bar_cover () {
    if ! check_start_from_steam ; then
        PW_GIF_FILE="$1"
        PW_GIF_SIZE_X=`file "${PW_GIF_FILE}" | awk '{print $7 + 7}'`
        PW_GIF_SIZE_Y=`file "${PW_GIF_FILE}" | awk '{print $9 + 7}'`
        "${pw_yad}" --picture --filename="${PW_GIF_FILE}" --close-on-unfocus --no-buttons --undecorated --center \
        --skip-taskbar --width=$PW_GIF_SIZE_X --height=$PW_GIF_SIZE_Y --window-icon="$PW_GUI_ICON_PATH/portproton.svg" > /dev/null 2>&1 &
        export PW_YAD_PID_PROGRESS_BAR_COVER="$!"
        return 0
    fi
}

pw_start_progress_bar_cover_block () {
    if ! check_start_from_steam ; then
        [[ ! -f "${pw_yad}" ]] && local pw_yad="yad"
        PW_GIF_FILE="$1"
        PW_GIF_SIZE_X=`file "${PW_GIF_FILE}" | awk '{print $7 + 7}'`
        PW_GIF_SIZE_Y=`file "${PW_GIF_FILE}" | awk '{print $9 + 7}'`
        "${pw_yad}" --picture --filename="${PW_GIF_FILE}" --close-on-unfocus --no-buttons --undecorated --center \
        --skip-taskbar --width=$PW_GIF_SIZE_X --height=$PW_GIF_SIZE_Y --window-icon="$PW_GUI_ICON_PATH/portproton.svg" > /dev/null 2>&1 &
        export PW_YAD_PID_PROGRESS_BAR_COVER_BLOCK="$!"
        return 0
    fi
}

pw_update_pfx_cover_gui () {
    if [[ "$1" == "winetricks" ]] ; then
        TAB_PLACE="--tab=$loc_gui_terminal!$PW_GUI_ICON_PATH/$TAB_SIZE.png --tab=$loc_gui_logo!$PW_GUI_ICON_PATH/$TAB_SIZE.png"
        TAB_N1=2
        TAB_N2=1
        YAD_UNDECORATED=""
    else
        TAB_PLACE="--tab=$loc_gui_logo!$PW_GUI_ICON_PATH/$TAB_SIZE.png --tab=$loc_gui_terminal!$PW_GUI_ICON_PATH/$TAB_SIZE.png"
        TAB_N1=1
        TAB_N2=2
        YAD_UNDECORATED="--undecorated --center"
    fi

    if ! check_start_from_steam && ! pgrep -a yad | grep "yad_v13_0 --notebook --key=$PW_KEY_PROGRESS_BAR_UP" &>/dev/null ; then
        PW_KEY_PROGRESS_BAR_UP=$RANDOM
        PW_GIF_FILE="${PW_GUI_ICON_PATH}/covers/update_prefix_${update_loc}.gif"
        PW_GIF_SIZE_X=`file "${PW_GIF_FILE}" | awk '{print $7 + 20}'`
        PW_GIF_SIZE_Y=`file "${PW_GIF_FILE}" | awk '{print $9 + 60}'`
        echo "UPDATE PREFIX..." > "${PORT_WINE_TMP_PATH}/update_pfx_log"
        export PW_TIMER=0
        while read -r line || [[ ! -z `pgrep -a yad | grep "yad_v13_0 --notebook --key=$PW_KEY_PROGRESS_BAR_UP" | awk '{print $1}'` ]] ; do
                sleep 0.005
                if [[ ! -z "${line}" ]] && [[ -z "`echo "${line}" | grep -i "gstreamer"`" ]] \
                                        && [[ -z "`echo "${line}" | grep -i "kerberos"`" ]] \
                                        && [[ -z "`echo "${line}" | grep -i "ntlm"`" ]]
                then
                    echo "# ${line}"
                fi
                if [[ "${PW_TIMER}" != 1 ]] ; then
                    sleep 3
                    PW_TIMER=1
                fi
        done < "${PORT_WINE_TMP_PATH}/update_pfx_log" | "${pw_yad_v13_0}" --plug=$PW_KEY_PROGRESS_BAR_UP --tabnum=$TAB_N2 --text-info --tail  2>/dev/null &
        "${pw_yad_v13_0}" --plug=$PW_KEY_PROGRESS_BAR_UP --tabnum=$TAB_N1 --picture --filename="${PW_GIF_FILE}" --image-on-top 2>/dev/null &

        "${pw_yad_v13_0}" --notebook --key="$PW_KEY_PROGRESS_BAR_UP" $TAB_PLACE --no-buttons --expand \
        --auto-close --skip-taskbar --width=$PW_GIF_SIZE_X --height=$PW_GIF_SIZE_Y $YAD_UNDECORATED \
        --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --title "PortProton" --tab-pos=bottom --expand 2>/dev/null &
        export PW_YAD_PID_PFX_COVER_UI="$!"
        return 0
    fi
}

pw_start_progress_bar_cs () {
    if ! check_start_from_steam ; then
        "${pw_yad}" --progress --progress-text="$@
        " --pulsate --close-on-unfocus --borders="$PROGRESS_BAR_BORDERS_SIZE" \
        --no-buttons --undecorated --center --skip-taskbar \
        --width="$PROGRESS_BAR_WIDTH_SIZE" \
        --wrap-width="$PROGRESS_BAR_WIDTH_SIZE" \
        --window-icon="$PW_GUI_ICON_PATH/portproton.svg" &>/dev/null &
        export PW_YAD_PID_PROGRESS_BAR_CS="$!"
        return 0
    fi
}

pw_start_progress_bar_block () {
    if ! check_start_from_steam ; then
        "${pw_yad}" --progress --progress-text="$@
        " --pulsate --borders="$PROGRESS_BAR_BORDERS_SIZE" \
        --no-buttons --undecorated --center --skip-taskbar \
        --width="$PROGRESS_BAR_WIDTH_SIZE" \
        --wrap-width="$PROGRESS_BAR_WIDTH_SIZE" \
        --window-icon="$PW_GUI_ICON_PATH/portproton.svg" &>/dev/null &
        export PW_YAD_PID_PROGRESS_BAR_BLOCK="$!"
        return 0
    fi
}

pw_stop_progress_bar () {
    for PW_KILL_YAD_PID in "$PW_YAD_PID_PROGRESS_BAR_BLOCK" "$PW_YAD_PID_PROGRESS_BAR_CS" \
                           "$PW_YAD_PID_PFX_COVER_UI" "$PW_YAD_PID_PROGRESS_BAR_COVER"
    do
        kill -s SIGUSR1 "$PW_KILL_YAD_PID" &>/dev/null
    done
    return 0
}
export -f pw_stop_progress_bar

pw_stop_progress_bar_cover () {
    kill -s KILL "$PW_YAD_PID_PROGRESS_BAR_COVER" &>/dev/null
    return 0
}
export -f pw_stop_progress_bar_cover

pw_stop_progress_bar_cover_block () {
    kill -s KILL "$PW_YAD_PID_PROGRESS_BAR_COVER_BLOCK" &>/dev/null
    return 0
}
export -f pw_stop_progress_bar_cover_block

open_changelog () {
    "${pw_yad}" --title="$loc_gui_changelog" --no-buttons --text-align=center \
    --text-info --show-uri --wrap --width=1200 --height=700 --uri-color=red \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" \
    --filename="${PORT_WINE_PATH}/data/${PW_CHANGELOG_FILE}" &>/dev/null
}
export -f open_changelog

pw_tray_icon () {
    if [ ! -z "`pgrep -a yad_v13_0 | grep "\--notification" | awk '{print $1}'`" ] ; then
        kill -s SIGUSR1 "`pgrep -a yad_v13_0 | grep "\--notification" | awk '{print $1}'`"
    fi

    tray_icon_click () {
        echo ""
    }
    export -f tray_icon_click

    pw_tray_winefile () {
        pw_run winefile "C:\\users\\${USER}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\"
    }
    export -f pw_tray_winefile

    pw_tray_taskmgr () {
        pw_run taskmgr
    }
    export -f pw_tray_taskmgr

    tray_icon_click_exit () {
        pw_stop_progress_bar
        stop_portwine
    }
    export -f tray_icon_click_exit

    # --window-icon="$PW_GUI_ICON_PATH/portproton_tray.png" \
    "${pw_yad_v13_0}" --notification --no-middle \
    --image="$PW_GUI_ICON_PATH/portproton_tray.png" \
    --command="bash -c tray_icon_click" \
    --tooltip="PortProton" \
    --icon-size=32 --menu="| \
  ${loc_tray_winefile}!bash -c pw_tray_winefile!"$PW_GUI_ICON_PATH/wine_file.png"|| \
  ${loc_tray_tascmng}!bash -c pw_tray_taskmgr!"$PW_GUI_ICON_PATH/wine_system.png"|| \
  ${loc_tray_cangelog}!bash -c open_changelog!"$PW_GUI_ICON_PATH/history.png"|| \
  ${loc_tray_force_exit}    !bash -c tray_icon_click_exit!"$PW_GUI_ICON_PATH/close.png"||" 2>/dev/null &

    return 0
}

pw_gui_for_edit_db () {
    KEY_EDIT_DB_GUI=$RANDOM
    if [[ "${PW_WINE_CPU_TOPOLOGY}" == *[0-9]:* ]] && [[ "${PW_WINE_CPU_TOPOLOGY}" != "disabled" ]] ; then
        CPU_LIMIT_VAR="`echo ${PW_WINE_CPU_TOPOLOGY%%:*}`"
    else
        CPU_LIMIT_VAR="disabled"
    fi
    # if [[ ! -z "${PW_AMD_VULKAN_USE}" ]] && [[ "${PW_AMD_VULKAN_USE}" != "disabled" ]] ; then
    #     AMD_VULKAN_VAR="${PW_AMD_VULKAN_USE}"
    # else
    #     AMD_VULKAN_VAR="disabled"
    # fi

    if [[ ! -z "${PW_GPU_USE}" ]] && [[ "${PW_GPU_USE}" != "disabled" ]] ; then
        GPU_VAR="${PW_GPU_USE}"
    else
        GPU_VAR="disabled"
    fi

    GET_GPU_NAMES=$("$PW_VULKANINFO_PORTABLE" 2>/dev/null | awk -F '=' '/deviceName/{print $2}' | sed '/llvm/d'| sort -u | sed 's/^ //' | paste -sd '!')

    logical_cores=$(grep -c "^processor" /proc/cpuinfo)
    if [[ "${logical_cores}" -le "4" ]] ; then
        GET_LOGICAL_CORE="1!$(seq -s! 1 $((${logical_cores} - 1)))"
    else
        GET_LOGICAL_CORE="1!2!$(seq -s! 4 4 $((${logical_cores} - 1)))"
    fi

    unset ADD_CHK_BOX_EDIT_DB
    edit_db_field_add () {
        for int_to_boole in $@ ; do
            if [ "${!int_to_boole}" == "1" ]
            then export ${int_to_boole}="TRUE"
            else export ${int_to_boole}="FALSE"
            fi
            TMP_HELP_FOR_GUI="${int_to_boole}_INFO"
            int_to_boole_non_pw="`echo ${int_to_boole} | sed 's/^PW_//' | sed 's/_/ /g' `"
            ADD_CHK_BOX_EDIT_DB+="--field=${CHKBOX_SPACE}${int_to_boole_non_pw}!${!TMP_HELP_FOR_GUI}:${THEME_CHKBOX}%${!int_to_boole}%"
        done
    }
    edit_db_field_add $@
    old_IFS=$IFS
    IFS="%"
    "${pw_yad_v13_0}" --plug=$KEY_EDIT_DB_GUI --tabnum="1" --form --separator=" " --columns=3 ${ADD_CHK_BOX_EDIT_DB} \
    1> "${PORT_WINE_TMP_PATH}/tmp_output_yad_edit_db" 2>/dev/null &
    IFS=$old_IFS

    case ${PW_WINDOWS_VER} in
         "7") ADD_WINVER_EDIT_DB="7!10!XP" ;;
        "XP") ADD_WINVER_EDIT_DB="XP!7!10" ;;
           *) ADD_WINVER_EDIT_DB="10!7!XP" ;;
    esac

    # --field="${loc_gui_amd_vulkan_select}!${loc_gui_amd_vulkan_select_help} :CB" "${AMD_VULKAN_VAR}!disabled!amdvlk!amdgpupro!radv!radv_gpl!radv_aco"

    "${pw_yad_v13_0}" --plug=$KEY_EDIT_DB_GUI --tabnum="2" --form --separator="%" --columns=1 \
    --field="${loc_gui_ver_windows}!${loc_gui_ver_windows_help} :CB" "${ADD_WINVER_EDIT_DB}" \
    --field="${loc_gui_aut_winetricks}!${loc_gui_aut_winetricks_help} :CBE" "${PW_DLL_INSTALL}!vcrun2019 corefonts lucida" \
    --field="${loc_gui_winedllover}!${loc_gui_winedllover_help} :CBE" "${WINEDLLOVERRIDES}!libglesv2=!d3dx9_36,d3dx9_42=n,b;mfc120=b,n" \
    --field=":LBL" "" \
    --field="${loc_gui_arg_exe}!${loc_gui_arg_exe_help} :CBE" "\\${LAUNCH_PARAMETERS[@]}!-dx11 -skipintro 1" \
    --field=":LBL" "" \
    --field="${loc_gui_cpu_limit}!${loc_gui_cpu_limit_help} :CB" "${CPU_LIMIT_VAR}!disabled!${GET_LOGICAL_CORE}" \
    --field="${loc_gui_gpu_select}!${loc_gui_gpu_select_help} :CB" "${GPU_VAR}!disabled!${GET_GPU_NAMES}" \
    --field="${loc_gui_arg_gamescope}!${loc_gui_arg_gamescope_help} :CBE" "\\${GAMESCOPE_ARGS}!-r 60 -F fsr!" 2>/dev/null 1> "${PORT_WINE_TMP_PATH}/tmp_output_yad_fps_limit" 2>/dev/null &

    "${pw_yad_v13_0}" --paned --key="$KEY_EDIT_DB_GUI" --title "EDIT_DB" --text-align=center --height="700" \
    --text "${loc_gui_edit_db} <b>${PORTWINE_DB}</b>\n ${loc_gui_edit_db_help}" --separator=" " \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" \
    --button="${loc_gui_cancel}"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"${loc_gui_cancel_help}":1 \
    --button="${loc_gui_reset_db}"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"${loc_gui_reset_db_help}":2 \
    --button="${loc_gui_open_db}"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"${loc_gui_open_db_help}":150 \
    --button="${loc_gui_save_changes}"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"${loc_gui_save_changes_help}":0 2>/dev/null
    YAD_STATUS="$?"
    export SKIP_CHECK_UPDATES=1
    case "$YAD_STATUS" in
          1)
                /usr/bin/env bash -c ${pw_full_command_line[*]} &
                exit 0
                ;;
          2)
                try_remove_file "$portwine_exe".ppdb
                /usr/bin/env bash -c ${pw_full_command_line[*]} &
                exit 0
                ;;
        252)
                exit 0
                ;;
    esac
    output_yad_edit_db=(`cat "${PORT_WINE_TMP_PATH}/tmp_output_yad_edit_db"`)
    bool_from_yad=0
    edit_db_field_read () {
        for boole_to_int in $@ ; do
            export ${boole_to_int}=${output_yad_edit_db[$bool_from_yad]}
            if [ "${!boole_to_int}" == "TRUE" ]
            then export ${boole_to_int}="1"
            else export ${boole_to_int}="0"
            fi
            export bool_from_yad=$(( ${bool_from_yad} + 1 ))
        done
    }
    edit_db_field_read $@
    PW_WINDOWS_VER="`cat "${PORT_WINE_TMP_PATH}/tmp_output_yad_fps_limit" | awk -F"%" '{print $1}'`"
    PW_DLL_INSTALL=`cat "${PORT_WINE_TMP_PATH}/tmp_output_yad_fps_limit" | awk -F"%" '{print $2}'`
    WINEDLLOVERRIDES=`cat "${PORT_WINE_TMP_PATH}/tmp_output_yad_fps_limit" | awk -F"%" '{print $3}'`
    LAUNCH_PARAMETERS=`cat "${PORT_WINE_TMP_PATH}/tmp_output_yad_fps_limit" | awk -F"%" '{print $5}'`
    CPU_LIMIT="`cat "${PORT_WINE_TMP_PATH}/tmp_output_yad_fps_limit" | awk -F"%" '{print $7}'`"
    PW_GPU_USE="`cat "${PORT_WINE_TMP_PATH}/tmp_output_yad_fps_limit" | awk -F"%" '{print $8}'`"
    GAMESCOPE_ARGS="`cat "${PORT_WINE_TMP_PATH}/tmp_output_yad_fps_limit" | awk -F"%" '{print $9}'`"
    # PW_AMD_VULKAN_USE="`cat "${PORT_WINE_TMP_PATH}/tmp_output_yad_fps_limit" | awk -F"%" '{print $10}'`"

    if [[ "${CPU_LIMIT}" != "disabled" ]] ; then
        export PW_WINE_CPU_TOPOLOGY="${CPU_LIMIT}:$(seq -s, 0 $((${CPU_LIMIT} - 1)))"
    else
        export PW_WINE_CPU_TOPOLOGY="disabled"
    fi
    echo "pw_gui_for_edit_db PORTWINE_DB_FILE=$PORTWINE_DB_FILE"
    edit_db_from_gui $@ LAUNCH_PARAMETERS PW_WINDOWS_VER PW_DLL_INSTALL WINEDLLOVERRIDES PW_WINE_CPU_TOPOLOGY GAMESCOPE_ARGS
    if [[ -z "$MANGOHUD_CONFIG" ]] ; then
        MONITOR_HEIGHT="$(echo $PW_SCREEN_RESOLUTION | awk -F'x' '{print $2}')"
        MH_FONT_SIZE="font_size=$(( MONITOR_HEIGHT / 45 ))"
        MANGOHUD_CONFIG="$DEFAULT_MANGOHUD_CONFIG,$MH_FONT_SIZE"
        edit_db_from_gui MANGOHUD_CONFIG
    fi
    edit_user_conf_from_gui PW_GPU_USE
    # PW_AMD_VULKAN_USE

    case "$YAD_STATUS" in
          0)
                print_info "Restarting PP after update ppdb file..."
                /usr/bin/env bash -c ${pw_full_command_line[*]} &
                exit 0
                ;;
        150)
                xdg-open "${PORTWINE_DB_FILE}" &
                exit 0
                ;;
    esac
}

gui_proton_downloader () {
    if [[ "$PW_WINE_USE" == PROTON_LG ]]
    then export PW_WINE_USE="${PW_PROTON_LG_VER}"
    elif [[ "$PW_WINE_USE" == WINE_*_LG ]] || [[ "$PW_WINE_USE" == WINE_LG ]]
    then export PW_WINE_USE="${PW_WINE_LG_VER}"
    fi
    if [[ "$1" == "silent" ]] && [[ -d "${PORT_WINE_PATH}/data/dist/${PW_WINE_USE}" ]] ; then
        return 0
    fi
    pw_start_progress_bar_block "$loc_gui_check_new_wine"
    # PROTON_GE
    export PROTON_GE_GIT=($(curl -s "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases" | grep "browser_download_url.*\.tar\.gz" | cut -d \" -f 4))
    try_remove_file "${PORT_WINE_TMP_PATH}/tmp_proton_ge_git"
    if [[ ! -z "${PROTON_GE_GIT}" ]] ; then
        for PGEGIT in ${PROTON_GE_GIT[@]} ; do
            echo ${PGEGIT} | awk -F/ '{print $NF}' | sed 's/.tar.gz//' >> "${PORT_WINE_TMP_PATH}/tmp_proton_ge_git"
        done
        sed -i '/Proton-6.5-GE-2/,$d' "${PORT_WINE_TMP_PATH}/tmp_proton_ge_git"
        sed -i '/github-action/d' "${PORT_WINE_TMP_PATH}/tmp_proton_ge_git"
    fi

    # WINE_KRON4EK
    export WINE_KRON4EK=($(curl -s "https://api.github.com/repos/Kron4ek/Wine-Builds/releases" | grep "browser_download_url.*\.tar\.xz" | cut -d \" -f 4))
    try_remove_file "${PORT_WINE_TMP_PATH}/tmp_wine_kron4ek_git"
    if [[ ! -z "${WINE_KRON4EK}" ]] ; then
        for PGEGIT in ${WINE_KRON4EK[@]} ; do
            echo ${PGEGIT} | awk -F/ '{print $NF}' | sed 's/.tar.xz//' >> "${PORT_WINE_TMP_PATH}/tmp_wine_kron4ek_git"
        done
        sed -i '/6.3/,$d' "${PORT_WINE_TMP_PATH}/tmp_wine_kron4ek_git"
        sed -i '/-x86/d' "${PORT_WINE_TMP_PATH}/tmp_wine_kron4ek_git"
    fi

    # WINE_GE_CUSTOM
    export WINE_GE_CUSTOM=($(curl -s "https://api.github.com/repos/GloriousEggroll/wine-ge-custom/releases" | grep "browser_download_url.*\.tar\.xz" | cut -d \" -f 4))
    try_remove_file "${PORT_WINE_TMP_PATH}/tmp_wine_ge_custom_git"
    if [[ ! -z "${WINE_GE_CUSTOM}" ]] ; then
        for PGEGIT in ${WINE_GE_CUSTOM[@]} ; do
            echo ${PGEGIT} | awk -F/ '{print $NF}' | sed 's/.tar.xz//' >> "${PORT_WINE_TMP_PATH}/tmp_wine_ge_custom_git"
        done
        sed -i '/6.23/,$d' "${PORT_WINE_TMP_PATH}/tmp_wine_ge_custom_git"
    fi

    # PROTON_LG
    export PROTON_PW_GIT=($(curl -s "https://api.github.com/repos/Castro-Fidel/wine_builds/releases" | grep "browser_download_url.*\.tar\.xz" | cut -d \" -f 4))
    try_remove_file "${PORT_WINE_TMP_PATH}/tmp_proton_pw_git"
    if [[ ! -z "${PROTON_PW_GIT}" ]] ; then
        for PPWGIT in ${PROTON_PW_GIT[@]} ; do
            echo ${PPWGIT} | awk -F/ '{print $NF}' | sed 's/.tar.xz//' >> "${PORT_WINE_TMP_PATH}/tmp_proton_pw_git"
        done
        sed -i /${PW_WINE_LG_VER}/d "${PORT_WINE_TMP_PATH}/tmp_proton_pw_git"
        sed -i '/plugins/d' "${PORT_WINE_TMP_PATH}/tmp_proton_pw_git"
    fi
    pw_stop_progress_bar
    if [[ -z "${PROTON_PW_GIT}" ]] ; then
        yad_error "$loc_gui_check_new_wine_error"
        export SKIP_CHECK_UPDATES=1
        /usr/bin/env bash -c ${pw_full_command_line[*]} &
        exit 0
    fi
    for INSTALLING_VERSION_IN_DIST in `ls "${PORT_WINE_PATH}/data/dist/"` ; do
        sed -i "/${INSTALLING_VERSION_IN_DIST}$/Id" "${PORT_WINE_TMP_PATH}/tmp_proton_ge_git"
        sed -i "/${INSTALLING_VERSION_IN_DIST}$/Id" "${PORT_WINE_TMP_PATH}/tmp_proton_pw_git"
        sed -i "/${INSTALLING_VERSION_IN_DIST}$/Id" "${PORT_WINE_TMP_PATH}/tmp_wine_kron4ek_git"
        sed -i "/${INSTALLING_VERSION_IN_DIST}$/Id" "${PORT_WINE_TMP_PATH}/tmp_wine_ge_custom_git"
    done
	# Installed wine
	ls -l ${PORT_WINE_PATH}/data/dist | awk '{print $9}' | sed '/^$/d' > ${PORT_WINE_TMP_PATH}/tmp_installed_wine
    if [[ "$1" != "silent" ]] ; then
        # GUI
        export KEY_WINE=$RANDOM
        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_proton_pw_set"
        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_kron4ek_set"
        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_proton_set"
        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_ge_custom_set"
        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_installed_wine_set"

        `"${pw_yad_v13_0}" --plug=$KEY_WINE --tabnum=1 --list --separator="" --listen \
        --column "$loc_gui_set_new_wine" < "${PORT_WINE_TMP_PATH}/tmp_proton_pw_git" 1> "${PORT_WINE_TMP_PATH}/tmp_proton_pw_set" 2>/dev/null` &
        `"${pw_yad_v13_0}" --plug=$KEY_WINE --tabnum=2 --list --separator="" --listen \
        --column "$loc_gui_set_new_wine" < "${PORT_WINE_TMP_PATH}/tmp_wine_kron4ek_git" 1> "${PORT_WINE_TMP_PATH}/tmp_kron4ek_set" 2>/dev/null` &
        `"${pw_yad_v13_0}" --plug=$KEY_WINE --tabnum=3 --list --separator="" --listen \
        --column "$loc_gui_set_new_wine" < "${PORT_WINE_TMP_PATH}/tmp_proton_ge_git" 1> "${PORT_WINE_TMP_PATH}/tmp_proton_set" 2>/dev/null` &
        `"${pw_yad_v13_0}" --plug=$KEY_WINE --tabnum=4 --list --separator="" --listen \
        --column "$loc_gui_set_new_wine" < "${PORT_WINE_TMP_PATH}/tmp_wine_ge_custom_git" 1> "${PORT_WINE_TMP_PATH}/tmp_ge_custom_set" 2>/dev/null` &
        `"${pw_yad_v13_0}" --plug=$KEY_WINE --tabnum=5 --list --separator="" --listen \
        --column "$loc_gui_del_wine" < "${PORT_WINE_TMP_PATH}/tmp_installed_wine" 1> "${PORT_WINE_TMP_PATH}/tmp_installed_wine_set" 2>/dev/null` &
        `"${pw_yad_v13_0}" --key=$KEY_WINE --notebook --width=500 --height=600 --text-align=center --no-button \
        --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --title "WINE MANAGER" --separator="" --expand \
        --tab-pos=top \
        --tab="PROTON-LG"!"$PW_GUI_ICON_PATH/$TAB_SIZE.png"!"" \
        --tab="WINE-KRON4EK"!"$PW_GUI_ICON_PATH/$TAB_SIZE.png"!"" \
        --tab="PROTON-GE"!"$PW_GUI_ICON_PATH/$TAB_SIZE.png"!"" \
        --tab="WINE-GE-CUSTOM"!"$PW_GUI_ICON_PATH/$TAB_SIZE.png"!"" \
        --tab="$loc_gui_installed_wine"!"$PW_GUI_ICON_PATH/$TAB_SIZE.png"!"" \
        --button="$loc_cancel"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"":1 \
        --button="OK"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"":0 2>/dev/null`
        YAD_WINE_STATUS="$?"
        if [[ "$YAD_WINE_STATUS" == "1" || "$YAD_WINE_STATUS" == "252" ]] ; then
            export SKIP_CHECK_UPDATES=1
            /usr/bin/env bash -c ${pw_full_command_line[*]} &
            exit 0
        fi

        if [ ! -z `cat "${PORT_WINE_TMP_PATH}/tmp_proton_set" | awk '{print $1}'` ] ; then
            export VERSION_WINE_GIT="`cat "${PORT_WINE_TMP_PATH}/tmp_proton_set"`"
        elif [ ! -z `cat "${PORT_WINE_TMP_PATH}/tmp_proton_pw_set" | awk '{print $1}'` ] ; then
            export VERSION_WINE_GIT="`cat "${PORT_WINE_TMP_PATH}/tmp_proton_pw_set"`"
        elif [ ! -z `cat "${PORT_WINE_TMP_PATH}/tmp_kron4ek_set" | awk '{print $1}'` ] ; then
            export VERSION_WINE_GIT="`cat "${PORT_WINE_TMP_PATH}/tmp_kron4ek_set"`"
        elif [ ! -z `cat "${PORT_WINE_TMP_PATH}/tmp_ge_custom_set" | awk '{print $1}'` ] ; then
            export VERSION_WINE_GIT="`cat "${PORT_WINE_TMP_PATH}/tmp_ge_custom_set"`"
        elif [ ! -z `cat "${PORT_WINE_TMP_PATH}/tmp_installed_wine_set" | awk '{print $1}'` ] ; then
            export VERSION_INSTALLED_WINE="`cat "${PORT_WINE_TMP_PATH}/tmp_installed_wine_set"`"
        else
            print_info "Nothing to do."
            export SKIP_CHECK_UPDATES=1
            /usr/bin/env bash -c ${pw_full_command_line[*]} &
            exit 0
        fi

        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_proton_pw_git"
        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_wine_kron4ek_git"
        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_proton_ge_git"
        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_wine_ge_custom_git"
        try_remove_file "${PORT_WINE_TMP_PATH}/tmp_installed_wine"

    elif [[ "$1" == "silent" ]] && [[ ! -z "$2" ]] ; then
        VERSION_WINE_GIT="$2"
    fi

    for GIVE_WINE_URL in ${PROTON_GE_GIT[@]} ${PROTON_PW_GIT[@]} ${WINE_KRON4EK[@]} ${WINE_GE_CUSTOM[@]} ; do
        if [ ! -z `echo ${GIVE_WINE_URL} | grep -i "${VERSION_WINE_GIT}"` ] ; then
            export URL_VERSION_PROTON_GIT="${GIVE_WINE_URL}"
            break
        fi
    done

	if [[ ! -z "${VERSION_INSTALLED_WINE}" ]]; then
		try_remove_dir "${PORT_WINE_PATH}/data/dist/${VERSION_INSTALLED_WINE}"
		unset VERSION_INSTALLED_WINE
        export SKIP_CHECK_UPDATES=1
        /usr/bin/env bash -c ${pw_full_command_line[*]} &
        exit 0
	fi

    print_info "Download and install ${VERSION_WINE_GIT}..."
    PW_WINE_ARCHIVE="$(echo ${URL_VERSION_PROTON_GIT} | awk -F'/' '{print $NF}' | awk -F'.tar' '{print $1}')"
    if try_download_to_path "${URL_VERSION_PROTON_GIT}" "${PORT_WINE_PATH}/data/tmp/" ; then
        for archive_type in "gz" "xz" ; do
            if [ -f "${PORT_WINE_PATH}/data/tmp/${PW_WINE_ARCHIVE}.tar.${archive_type}" ] ; then
                if unpack_tar_${archive_type} "${PORT_WINE_PATH}/data/tmp/${PW_WINE_ARCHIVE}.tar.${archive_type}" "${PORT_WINE_PATH}/data/dist/" ; then
                    try_remove_file "${PORT_WINE_PATH}/data/tmp/${PW_WINE_ARCHIVE}.tar.${archive_type}"
                    if [ ! -z "${portwine_exe}" ]; then
                        PW_WINE_USE="$(echo ${VERSION_WINE_GIT} | tr [[:lower:]] [[:upper:]])"
                        edit_db_from_gui PW_WINE_USE
                    fi
                else
                    try_remove_file "${PORT_WINE_PATH}/data/tmp/${PW_WINE_ARCHIVE}.tar.${archive_type}"
                    try_remove_dir "${PORT_WINE_PATH}/data/dist/${PW_WINE_ARCHIVE}"
                    yad_error_download && gui_proton_downloader || exit 1
                fi
            fi
        done
    else
        yad_error_download && gui_proton_downloader || exit 1
    fi

    if [[ "$1" != "silent" ]] ; then
        export SKIP_CHECK_UPDATES=1
        edit_db_from_gui
        /usr/bin/env bash -c ${pw_full_command_line[*]} &
        exit 0
    else
        init_wine_ver
    fi
}
export -f gui_proton_downloader

gui_vkBasalt () {
    KEY_FX_GUI=$RANDOM
    FILE_VKBASALT_CONF="${PORT_WINE_PATH}/data/vkBasalt.conf"
    LIST_FX=(`grep -E '.fx$|.fxh$' "${FILE_VKBASALT_CONF}" | awk '{print $1}'`)
    GET_FX_IN_FILE=(`echo ${PW_VKBASALT_EFFECTS} | sed s/"cas:"// | sed s/":"/" "/g`)
    unset ADD_GUI_FX GUI_FX_RESULT
    for add_list_fx in ${LIST_FX[@]} ; do
        PW_VKBASALT_GUI_HELP="PW_${add_list_fx}_INFO"
        if [[ ! -z `echo " ${GET_FX_IN_FILE[@]} " | grep " ${add_list_fx} "` ]] ; then
            ADD_GUI_FX+="--field=${CHKBOX_SPACE}${add_list_fx}!${!PW_VKBASALT_GUI_HELP}:${THEME_CHKBOX}%TRUE%"
        else
            ADD_GUI_FX+="--field=${CHKBOX_SPACE}${add_list_fx}!${!PW_VKBASALT_GUI_HELP}:${THEME_CHKBOX}%FALSE%"
        fi
    done
    if [[ ! -z "${PW_VKBASALT_FFX_CAS}" ]] ; then
        if [[ "$PW_VKBASALT_FFX_CAS" == "0" ]]
        then export VKBASALT_FFX_CAS_GUI="0"
        elif [[ "$PW_VKBASALT_FFX_CAS" == "1" ]]
        then export VKBASALT_FFX_CAS_GUI="100"
        elif [[ "$PW_VKBASALT_FFX_CAS" == 0.0* ]]
        then export VKBASALT_FFX_CAS_GUI="$(echo "$PW_VKBASALT_FFX_CAS" | awk -F'0.0' '{print $2}')"
        else export VKBASALT_FFX_CAS_GUI="$(echo "$PW_VKBASALT_FFX_CAS" | awk -F'0.' '{print $2}')"
        fi
    else
        VKBASALT_FFX_CAS_GUI=66
    fi
    export old_IFS=$IFS
    export IFS="%"
    "${pw_yad_v13_0}" --plug=$KEY_FX_GUI --tabnum="1" --form --columns=4 --separator=" " \
    --text-align=center --text="$loc_gui_vkbasalt_top" \
    ${ADD_GUI_FX} 1> "${PORT_WINE_TMP_PATH}/tmp_yad_basalt_set" 2>/dev/null &
    export IFS="${old_IFS}"

    "${pw_yad_v13_0}" --plug=$KEY_FX_GUI --tabnum="2" --separator=" " --form \
    --field="AMD FidelityFX - Contrast Adaptive Sharpening"!"$loc_gui_ffx_cas":SCL "${VKBASALT_FFX_CAS_GUI}" \
    1> "${PORT_WINE_TMP_PATH}/tmp_yad_cas_set" 2>/dev/null &

    "${pw_yad_v13_0}" --paned --key="$KEY_FX_GUI" --height="625" --title="vkBasalt" --center \
    --separator=" " --window-icon="$PW_GUI_ICON_PATH/portproton.svg" \
    --button="$loc_gui_cancel"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"$loc_gui_cancel_help":1 \
    --button="$loc_gui_disabled_vkbas"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"$loc_gui_disabled_vkbas_help":180 \
    --button="$loc_gui_save_changes"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"$loc_gui_save_changes_help":182 2>/dev/null
    YAD_VKBASALT_STATUS="$?"
    case "${YAD_VKBASALT_STATUS}" in
        1|252)
            export SKIP_CHECK_UPDATES=1
            /usr/bin/env bash -c ${pw_full_command_line[*]} &
            exit 0 ;;
        180)
            export ENABLE_VKBASALT=0 ;;
        182)
            export ENABLE_VKBASALT=1 ;;
    esac
    YAD_BASALT_SET=`cat "${PORT_WINE_TMP_PATH}/tmp_yad_basalt_set"`
    YAD_CAS_SET=`cat "${PORT_WINE_TMP_PATH}/tmp_yad_cas_set" | sed s/" "//g`

    INT_COUNT_FX=0
    for read_list_fx in ${YAD_BASALT_SET} ; do
        if [[ "$read_list_fx" == "TRUE" ]] ; then
            export GUI_FX_RESULT+="${LIST_FX[$INT_COUNT_FX]}:"
        fi
        ((INT_COUNT_FX++))
    done
    GUI_FX_RESULT="${GUI_FX_RESULT}cas"
    export PW_VKBASALT_EFFECTS="${GUI_FX_RESULT}"

    if [[ "$YAD_CAS_SET" == "0" ]]
    then export PW_VKBASALT_FFX_CAS="0"
    elif [[ "$YAD_CAS_SET" == "100" ]]
    then export PW_VKBASALT_FFX_CAS="1"
    elif [[ "$YAD_CAS_SET" -lt 10 ]]
    then export PW_VKBASALT_FFX_CAS="0.0$YAD_CAS_SET"
    else export PW_VKBASALT_FFX_CAS="0.$YAD_CAS_SET"
    fi
    edit_db_from_gui PW_VKBASALT_EFFECTS PW_VKBASALT_FFX_CAS ENABLE_VKBASALT
    export SKIP_CHECK_UPDATES=1
    /usr/bin/env bash -c ${pw_full_command_line[*]} &
    exit 0
}

gui_MangoHud () {
    KEY_MH_GUI=$RANDOM
    LIST_MH=(
        arch battery battery_icon battery_time battery_watt core_bars core_load
        cpu_mhz cpu_power cpu_temp device_battery_icon engine_short_names
        engine_version exec_name fcat fps_metrics frame_count frametime full
        gamemode gpu_core_clock gpu_fan gpu_junction_temp gpu_mem_clock
        gpu_mem_temp gpu_name gpu_power gpu_temp gpu_voltage histogram horizontal
        horizontal_stretch hud_compact hud_no_margin io_read io_write no_display
        no_small_font procmem procmem_shared procmem_virt ram resolution
        show_fps_limit swap temp_fahrenheit throttling_status throttling_status_graph
        time version vkbasalt vram vulkan_driver wine
    )
    # fps_only

    unset ADD_GUI_MH GUI_MH_RESULT

    GET_REFRESH_RATE="30!45!60!75!120!144!165!240"

    if [[ -z "$FPS_LIMIT" ]]; then
        FPS_LIMIT_VAR="disabled"
    else
        FPS_LIMIT_VAR="${FPS_LIMIT}"
    fi

    if [ -n "$MANGOHUD_CONFIG" ]; then
        PW_MANGOHUD_CONFIG=($(echo "$MANGOHUD_CONFIG" | tr ',' '\n' | grep -v '='))
    else
        PW_MANGOHUD_CONFIG=($(echo "$DEFAULT_MANGOHUD_CONFIG" | tr ',' '\n' | grep -v '='))
    fi

            # !!!

    for add_list_mh in "${LIST_MH[@]}"; do
        PW_MH_GUI_HELP="PW_MH_${add_list_mh}_INFO"
        if [[ -n "$(grep -wo "$add_list_mh" <<<"${PW_MANGOHUD_CONFIG[@]}")" ]] ; then
            ADD_GUI_MH+="--field=${CHKBOX_SPACE}$(echo ${add_list_mh} | sed 's/_/ /g' | tr [[:lower:]] [[:upper:]])!${!PW_MH_GUI_HELP}:${THEME_CHKBOX}%TRUE%"
        else
            ADD_GUI_MH+="--field=${CHKBOX_SPACE}$(echo ${add_list_mh} | sed 's/_/ /g' | tr [[:lower:]] [[:upper:]])!${!PW_MH_GUI_HELP}:${THEME_CHKBOX}%FALSE%"
        fi
    done

    export old_IFS=$IFS
    export IFS="%"
    "${pw_yad_v13_0}" --plug=$KEY_MH_GUI --tabnum="1" --form --columns=4 --separator=" " \
        --text-align=center --text="$loc_gui_mh_top" \
        ${ADD_GUI_MH} 1> "${PORT_WINE_TMP_PATH}/tmp_yad_mh_set" 2>/dev/null &
    export IFS="${old_IFS}"

    "${pw_yad_v13_0}" --plug=$KEY_MH_GUI --tabnum="2" --separator=" " --form \
        --field="${loc_gui_mango_fps}!${loc_gui_mango_fps_help} :CB" "${FPS_LIMIT_VAR}!disabled!${GET_REFRESH_RATE}" \
        1> "${PORT_WINE_TMP_PATH}/tmp_yad_mh_fps_limit" 2>/dev/null &

    "${pw_yad_v13_0}" --paned --key="$KEY_MH_GUI" --height="575" --title="MangoHud" --center \
        --separator=" " --window-icon="$PW_GUI_ICON_PATH/portproton.svg" \
        --button="$loc_gui_cancel"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"$loc_gui_cancel_help":1 \
        --button="$loc_gui_disabled_mh"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"$loc_gui_disabled_mh_help":182 \
        --button="$loc_gui_save_changes"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"$loc_gui_save_changes_help":184 2>/dev/null
    YAD_MANGOHUD_STATUS="$?"

    case "${YAD_MANGOHUD_STATUS}" in
        1 | 252)
            export SKIP_CHECK_UPDATES=1
            /usr/bin/env bash -c "${pw_full_command_line[*]}" &
            exit 0
            ;;
        182)
            export PW_MANGOHUD=0
            export FPS_LIMIT="disabled"
            edit_db_from_gui PW_MANGOHUD FPS_LIMIT
            export SKIP_CHECK_UPDATES=1
            /usr/bin/env bash -c "${pw_full_command_line[*]}" &
            exit 0
            ;;
        184)
            export PW_MANGOHUD=1
            ;;
    esac

    YAD_MH_SET=$(<"${PORT_WINE_TMP_PATH}/tmp_yad_mh_set")
    FPS_LIMIT=$(cat "${PORT_WINE_TMP_PATH}/tmp_yad_mh_fps_limit" | awk '{print $1}')

    MONITOR_HEIGHT="$(echo $PW_SCREEN_RESOLUTION | awk -F'x' '{print $2}')"
    MH_FONT_SIZE="font_size=$(( MONITOR_HEIGHT / 45 ))"


    export INT_COUNT_MH=0
    for read_list_mh in ${YAD_MH_SET} ; do
        if [[ "$read_list_mh" == "TRUE" ]]
        then export GUI_MH_RESULT+="$(echo "${LIST_MH[$INT_COUNT_MH]}," | sed 's/ /_/g' | tr [[:upper:]] [[:lower:]] )"
        fi
        ((INT_COUNT_MH++))
    done

    if [[ -n "$MH_FONT_SIZE" ]]
    then GUI_MH_RESULT="${GUI_MH_RESULT}${MH_FONT_SIZE}"
    else GUI_MH_RESULT="${GUI_MH_RESULT%,}"
    fi

    if [[ "${FPS_LIMIT}" != "disabled" ]] ; then
        export GUI_MH_RESULT=${GUI_MH_RESULT},fps_limit=${FPS_LIMIT}
        export PW_MANGOHUD=1
    elif [[ "${FPS_LIMIT}" == "disabled" ]]
    then export GUI_MH_RESULT="$(echo ${GUI_MH_RESULT} | sed "s/,fps_limit=${FPS_LIMIT_VAR}//" | sed "s/,fps_limit=disabled//")"
    fi

    if [[ "${GUI_MH_RESULT}" =~ "fps_only" ]]; then
        export GUI_MH_RESULT="fps_only"
        print_info "In the MangoHud config fps_only is detected all settings are reseted"
    fi

    export MANGOHUD_CONFIG="${GUI_MH_RESULT}"

    edit_db_from_gui MANGOHUD_CONFIG PW_MANGOHUD FPS_LIMIT
    export SKIP_CHECK_UPDATES=1
    /usr/bin/env bash -c ${pw_full_command_line[*]} &
    exit 0
}

portwine_create_shortcut () {
    pw_create_gui_png
    pw_stop_progress_bar

    if [[ "$1" == "block_name" ]] ; then
        export name_desktop="${PORTPROTON_NAME}"
        OUTPUT=$("${pw_yad}" --title="${inst_set}." --form \
        --window-icon "$PW_GUI_ICON_PATH/portproton.svg" \
        --image "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" \
        --field="${sc_info}":LBL "" \
        --field="  ${name_desktop}":LBL "" \
        --field="  ${sc_menu_desktop}":CHK "TRUE" \
        --field="  ${sc_desktop_desktop}":CHK "TRUE" \
        --field="  ${sc_add_in_steam}":CHK "FALSE" \
        --button="$loc_gui_create_shortcut"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":0)
        PW_YAD_OUT=$?
    else
        export name_desktop="${PORTPROTON_NAME}"
        OUTPUT=$("${pw_yad}" --title="${inst_set}." --form \
        --window-icon "$PW_GUI_ICON_PATH/portproton.svg" \
        --image "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" \
        --field="${sc_info}":LBL "" \
        --field="${sc_name}:" "${name_desktop}" \
        --field="  ${sc_menu_desktop}":CHK "TRUE" \
        --field="  ${sc_desktop_desktop}":CHK "TRUE" \
        --field="  ${sc_add_in_steam}":CHK "FALSE" \
        --button="$loc_gui_create_shortcut"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":0)
        PW_YAD_OUT=$?
    fi

    if [[ "$PW_YAD_OUT" == "0" ]] ; then
        if [[ "$1" == "block_name" ]]
        then name_desktop="$PORTWINE_CREATE_SHORTCUT_NAME"
        else name_desktop=$(echo "$OUTPUT" | awk -F'|' '{print $2}')
        fi
        create_menu_desktop_shortcut=$(echo "$OUTPUT" | awk -F'|' '{print $3}')
        create_desktop_desktop_shortcut=$(echo "$OUTPUT" | awk -F'|' '{print $4}')
        create_menu_steam_shortcut=$(echo "$OUTPUT" | awk -F'|' '{print $5}')

        try_remove_file "${PORT_WINE_PATH}/${name_desktop}.desktop"

        if [[ "${PORTPROTON_NAME}" != "${name_desktop}" ]]
        then mv -f "${PORT_WINE_PATH}/data/img/${PORTPROTON_NAME}.png" "${PORT_WINE_PATH}/data/img/${name_desktop}.png"
        fi

        echo "[Desktop Entry]" > "${PORT_WINE_PATH}/${name_desktop}.desktop"
        echo "Name=${name_desktop}" >> "${PORT_WINE_PATH}/${name_desktop}.desktop"
        if check_flatpak
        then echo "Exec=flatpak run ru.linux_gaming.PortProton \"${portwine_exe}\" " >> "${PORT_WINE_PATH}/${name_desktop}.desktop"
        else echo "Exec=env "\"${PORT_SCRIPTS_PATH}/start.sh\" \"${portwine_exe}\" "" >> "${PORT_WINE_PATH}/${name_desktop}.desktop"
        fi
        echo "Type=Application" >> "${PORT_WINE_PATH}/${name_desktop}.desktop"
        echo "Categories=Game" >> "${PORT_WINE_PATH}/${name_desktop}.desktop"
        echo "StartupNotify=true" >> "${PORT_WINE_PATH}/${name_desktop}.desktop"
        echo "Path="${PORT_SCRIPTS_PATH}/"" >> "${PORT_WINE_PATH}/${name_desktop}.desktop"
        echo "Icon="${PORT_WINE_PATH}/data/img/${name_desktop}.png"" >> "${PORT_WINE_PATH}/${name_desktop}.desktop"
        chmod u+x "${PORT_WINE_PATH}/${name_desktop}.desktop"

        if [[ "${create_menu_desktop_shortcut}" == "TRUE" ]] ; then
            try_remove_file "${HOME}/.local/share/applications/${name_desktop}.desktop"
            cp -f "${PORT_WINE_PATH}/${name_desktop}.desktop" "${HOME}/.local/share/applications/"
        fi

        if [[ "${create_desktop_desktop_shortcut}" == "TRUE" ]] ; then
            if [[ -d "${HOME}/Desktop" ]] ; then
                cp -f "${PORT_WINE_PATH}/${name_desktop}.desktop" "${HOME}/Desktop/"
            elif [[ -d "${HOME}/Рабочий стол" ]] ; then
                cp -f "${PORT_WINE_PATH}/${name_desktop}.desktop" "${HOME}/Рабочий стол/"
            elif [[ $(xdg-user-dir DESKTOP) ]] ; then
                cp -f "${PORT_WINE_PATH}/${name_desktop}.desktop" "$(xdg-user-dir DESKTOP)"
            fi
        fi

        if [[ "${create_menu_steam_shortcut}" == "TRUE" ]] ; then
            export STEAM_SCRIPTS="${PORT_WINE_PATH}/steam_scripts"
            create_new_dir "${STEAM_SCRIPTS}"
            echo "#!/usr/bin/env bash" > "${STEAM_SCRIPTS}/${name_desktop}.sh"
            echo "export START_FROM_STEAM=1" >> "${STEAM_SCRIPTS}/${name_desktop}.sh"
            echo "export LD_PRELOAD=" >> "${STEAM_SCRIPTS}/${name_desktop}.sh"
            if check_flatpak
            then echo "flatpak run ru.linux_gaming.PortProton \"${portwine_exe}\" " >> "${STEAM_SCRIPTS}/${name_desktop}.sh"
            else echo "\"${PORT_SCRIPTS_PATH}/start.sh\" \"${portwine_exe}\" " >> "${STEAM_SCRIPTS}/${name_desktop}.sh"
            fi
            chmod u+x "${STEAM_SCRIPTS}/${name_desktop}.sh"
            export SCVDF="shortcuts.vdf"
            for STUIDPATH in "${HOME}"/.local/share/Steam/userdata/*/ ; do
                create_new_dir "${STUIDPATH}/config/"
                export SCPATH="${STUIDPATH}/config/$SCVDF"
                "${PORT_SCRIPTS_PATH}/add_in_steam.sh"
            done
            if [[ "${PW_SKIP_RESTART_STEAM}" != 1 ]] && pgrep -i steam &>/dev/null ; then
                if yad_question "$sc_restert_steam" ; then
                    pw_start_progress_bar_block "Restarting STEAM... Please wait."
                    kill -s SIGTERM $(pgrep -a steam) &>/dev/null
                    while pgrep -i steam &>/dev/null ; do
                        sleep 0.5
                    done
                    steam &
                    sleep 5
                    pw_stop_progress_bar
                    exit 0
                fi
            fi
            unset PW_SKIP_RESTART_STEAM
        fi

        [[ "$1" != silent ]] && [[ "${PW_SKIP_RESTART_STEAM}" != 1 ]] && "${PORT_WINE_PATH}" 2>1 >/dev/null &
    fi
}

portwine_delete_shortcut () {
    rm -f "$(grep -il "${portwine_exe}" "${HOME}/.local/share/applications"/*.desktop)" &>/dev/null
    rm -f "$(grep -il "${portwine_exe}" "${PORT_WINE_PATH}"/*.desktop)" &>/dev/null
    # rm -f "$(grep -il "${portwine_exe}" "${STEAM_SCRIPTS}"/*.sh)" &>/dev/null
    if [[ -d "${HOME}/Desktop" ]] ; then
        rm -f "$(grep -il "${portwine_exe}" "${HOME}/Desktop"/*.desktop)" &>/dev/null
    elif [[ -d "${HOME}/Рабочий стол" ]] ; then
        rm -f "$(grep -il "${portwine_exe}" "${HOME}/Рабочий стол"/*.desktop)" &>/dev/null
    elif [[ $(xdg-user-dir DESKTOP) ]] ; then
        rm -f "$(grep -il "${portwine_exe}" "$(xdg-user-dir DESKTOP)"/*.desktop)" &>/dev/null
    fi
}

portwine_missing_shortcut () {
    "${pw_yad}" --title="${loc_gui_error}." --form \
    --window-icon "$PW_GUI_ICON_PATH/portproton.svg" \
    --image "$PW_GUI_ICON_PATH/error_file.png" \
    --text "$loc_gui_missing_shortcut" \
    --button="$loc_gui_delete_shortcut"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":0 \
    --button="$loc_cancel"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":1
    if [ $? -eq "0" ] ; then
        portwine_delete_shortcut
    fi
    exit 0
}

pw_prefix_manager () {
    update_winetricks
    start_portwine
    if [ ! -f "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ] ; then
        touch "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
    fi

    pw_start_progress_bar_block "$loc_start_pfx_manager $PW_PREFIX_NAME"
    "${PORT_WINE_TMP_PATH}/winetricks" dlls list | awk -F'(' '{print $1}' 1> "${PORT_WINE_TMP_PATH}/dll_list"
    "${PORT_WINE_TMP_PATH}/winetricks" fonts list | awk -F'(' '{print $1}' 1> "${PORT_WINE_TMP_PATH}/fonts_list"
    "${PORT_WINE_TMP_PATH}/winetricks" settings list | awk -F'(' '{print $1}' 1> "${PORT_WINE_TMP_PATH}/settings_list"

    gui_prefix_manager () {
        unset SET_FROM_PFX_MANAGER_TMP SET_FROM_PFX_MANAGER
        old_IFS=$IFS
        IFS=$'\n'
        try_remove_file  "${PORT_WINE_TMP_PATH}/dll_list_tmp"
        while read PW_BOOL_IN_DLL_LIST ; do
            if [[ -z $(echo "${PW_BOOL_IN_DLL_LIST}" | grep -E 'd3d|directx9|dont_use|dxvk|vkd3d|galliumnine|faudio1') ]] ; then
                if grep "^$(echo ${PW_BOOL_IN_DLL_LIST} | awk '{print $1}')$" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ; then
                    echo -e "true\n$(echo ${PW_BOOL_IN_DLL_LIST} | awk '{print $1}')\n`echo ${PW_BOOL_IN_DLL_LIST} | awk '{ $1 = ""; print substr($0, 2) }'`" >> "${PORT_WINE_TMP_PATH}/dll_list_tmp"
                else
                    echo -e "false\n`echo "${PW_BOOL_IN_DLL_LIST}" | awk '{print $1}'`\n`echo ${PW_BOOL_IN_DLL_LIST} | awk '{ $1 = ""; print substr($0, 2) }'`" >> "${PORT_WINE_TMP_PATH}/dll_list_tmp"
                fi
            fi
        done < "${PORT_WINE_TMP_PATH}/dll_list"
        try_remove_file  "${PORT_WINE_TMP_PATH}/fonts_list_tmp"
        while read PW_BOOL_IN_FONTS_LIST ; do
            if [[ -z $(echo "${PW_BOOL_IN_FONTS_LIST}" | grep -E 'dont_use') ]] ; then
                if grep "^$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{print $1}')$" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ; then
                    echo -e "true\n$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{print $1}')\n$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{ $1 = ""; print substr($0, 2) }')" >> "${PORT_WINE_TMP_PATH}/fonts_list_tmp"
                else
                    echo -e "false\n$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{print $1}')\n$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{ $1 = ""; print substr($0, 2) }')" >> "${PORT_WINE_TMP_PATH}/fonts_list_tmp"
                fi
            fi
        done < "${PORT_WINE_TMP_PATH}/fonts_list"
        try_remove_file  "${PORT_WINE_TMP_PATH}/settings_list_tmp"
        while read PW_BOOL_IN_FONTS_LIST ; do
            if [[ -z $(echo "${PW_BOOL_IN_FONTS_LIST}" | grep -E 'vista|alldlls|autostart_|bad|good|win|videomemory|vd=|isolate_home') ]] ; then
                if grep "^$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{print $1}')$" "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ; then
                    echo -e "true\n$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{print $1}')\n$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{ $1 = ""; print substr($0, 2) }')" >> "${PORT_WINE_TMP_PATH}/settings_list_tmp"
                else
                    echo -e "false\n$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{print $1}')\n$(echo "${PW_BOOL_IN_FONTS_LIST}" | awk '{ $1 = ""; print substr($0, 2) }')" >> "${PORT_WINE_TMP_PATH}/settings_list_tmp"
                fi
            fi
        done < "${PORT_WINE_TMP_PATH}/settings_list"
        pw_stop_progress_bar

        KEY_EDIT_MANAGER_GUI=$RANDOM
        "${pw_yad_v13_0}" --plug=$KEY_EDIT_MANAGER_GUI --tabnum=1 --list --checklist \
        --text="${loc_prefix_manager_comp} <b>\"${PW_PREFIX_NAME}\"</b>, ${loc_prefix_manager_wine} <b>\"${PW_WINE_USE}\"</b>" \
        --column=set --column=dll --column=info < "${PORT_WINE_TMP_PATH}/dll_list_tmp" 1>> "${PORT_WINE_TMP_PATH}/to_winetricks" 2>/dev/null &

        "${pw_yad_v13_0}" --plug=$KEY_EDIT_MANAGER_GUI --tabnum=2 --list --checklist \
        --text="${loc_prefix_manager_font} <b>\"${PW_PREFIX_NAME}\"</b>, ${loc_prefix_manager_wine} <b>\"${PW_WINE_USE}\"</b>" \
        --column=set --column=dll --column=info < "${PORT_WINE_TMP_PATH}/fonts_list_tmp" 1>> "${PORT_WINE_TMP_PATH}/to_winetricks" 2>/dev/null &

        "${pw_yad_v13_0}" --plug=$KEY_EDIT_MANAGER_GUI --tabnum=3 --list --checklist \
        --text="${loc_prefix_manager_conf} <b>\"${PW_PREFIX_NAME}\"</b>" \
        --column=set --column=dll --column=info < "${PORT_WINE_TMP_PATH}/settings_list_tmp" 1>> "${PORT_WINE_TMP_PATH}/to_winetricks" 2>/dev/null &

        "${pw_yad_v13_0}" --key=$KEY_EDIT_MANAGER_GUI --notebook \
        --width=900 --height=800 --expand \
        --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --title "$loc_pm" \
        --button="$loc_cancel"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"":1 \
        --button="OK"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png"!"":0 \
        --tab-pos=bottom \
        --tab="$loc_pm_dlls"!"$PW_GUI_ICON_PATH/$TAB_SIZE.png"!"" \
        --tab="$loc_pm_fonts"!"$PW_GUI_ICON_PATH/$TAB_SIZE.png"!"" \
        --tab="$loc_pm_settings"!"$PW_GUI_ICON_PATH/$TAB_SIZE.png"!"" 2>/dev/null
        YAD_STATUS="$?"
        if [[ "$YAD_STATUS" == "1" || "$YAD_STATUS" == "252" ]] ; then
            print_info "Nothing to do. Restarting PortProton..."
            stop_portwine &
            /usr/bin/env bash -c ${pw_full_command_line[*]} &
            exit 0
        fi
        try_remove_file  "${PORT_WINE_TMP_PATH}/dll_list_tmp"
        try_remove_file  "${PORT_WINE_TMP_PATH}/fonts_list_tmp"
        try_remove_file  "${PORT_WINE_TMP_PATH}/settings_list_tmp"

        for STPFXMNG in $(cat "${PORT_WINE_TMP_PATH}/to_winetricks") ; do
            grep $(echo ${STPFXMNG} | awk -F'|' '{print $2}') "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" &>/dev/null
            if [ "$?" == "1" ] ; then
                [[ ! -z "${STPFXMNG}" ]] && SET_FROM_PFX_MANAGER+="$(echo "${STPFXMNG}" | awk -F'|' '{print $2}') "
            fi
        done
        IFS=${old_IFS}
        try_remove_file  "${PORT_WINE_TMP_PATH}/to_winetricks"

        if [[ ! -z ${SET_FROM_PFX_MANAGER} ]] ; then
            pw_update_pfx_cover_gui "winetricks"
            echo "START WINETRICKS..." >> "${PORT_WINE_TMP_PATH}/update_pfx_log"
            echo "Try to install DLL in prefix: ${SET_FROM_PFX_MANAGER}" >> "${PORT_WINE_TMP_PATH}/update_pfx_log"
            print_info "Try to install DLL in prefix: ${SET_FROM_PFX_MANAGER}"
            ${pw_runtime} env PATH="${PATH}" LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" GST_PLUGIN_SYSTEM_PATH_1_0="" \
            "${PORT_WINE_TMP_PATH}/winetricks" -q -r -f ${SET_FROM_PFX_MANAGER} | tee -a "${PORT_WINE_TMP_PATH}/update_pfx_log"
            wait_wineserver
            kill_portwine
            pw_stop_progress_bar
            gui_prefix_manager
        else
            print_info "Nothing to do. Restarting PortProton..."
            stop_portwine &
            /usr/bin/env bash -c ${pw_full_command_line[*]} &
            exit 0
        fi
    }
    gui_prefix_manager
}

portwine_start_debug () {
    kill_portwine
    export PW_LOG=1
    if [[ -z "$VULKAN_DRIVER_NAME" ]] || [[ "$VULKAN_DRIVER_NAME" == "llvmpipe" ]] ; then
	yad_info "Attention working version of vulkan not detected!\nIt is recommended to run games in OpenGL (low performance possible)!"
    fi
    echo "${port_deb1}" > "${PORT_WINE_PATH}/${portname}.log"
    echo "${port_deb2}" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-------------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "PortWINE version:" >> "${PORT_WINE_PATH}/${portname}.log"
    read install_ver < "${PORT_WINE_TMP_PATH}/${portname}_ver"
    echo "${portname}-${install_ver}" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "------------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Scripts version:" >> "${PORT_WINE_PATH}/${portname}.log"
    cat "${PORT_WINE_TMP_PATH}/scripts_ver" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-----------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    if [ "${PW_USE_RUNTIME}" = 0 ] ; then
        echo "RUNTIME is disabled" >> "${PORT_WINE_PATH}/${portname}.log"
    else
        echo "RUNTIME is enabled" >> "${PORT_WINE_PATH}/${portname}.log"
    fi
    echo "----------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    if [ ! -z "${portwine_exe}" ] ; then
        echo "Debug for programm:" >> "${PORT_WINE_PATH}/${portname}.log"
        echo "${portwine_exe}" >> "${PORT_WINE_PATH}/${portname}.log"
        echo "---------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    fi
    echo "GLIBC version:" >> "${PORT_WINE_PATH}/${portname}.log"
    echo $(ldd --version | grep -m1 ldd | awk '{print $NF}') >> "${PORT_WINE_PATH}/${portname}.log"
    echo "--------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    if [[ "${PW_VULKAN_USE}" = "0" ]] ; then
        echo "PW_VULKAN_USE=${PW_VULKAN_USE} - DX9-11 to ${loc_gui_open_gl}" >> "${PORT_WINE_PATH}/${portname}.log"
    elif [[ "${PW_VULKAN_USE}" = "1" ]] ; then
        echo "PW_VULKAN_USE=${PW_VULKAN_USE} - DXVK v.${DXVK_STABLE_VER} and VKD3D-PROTON v.${VKD3D_STABLE_VER}" >> "${PORT_WINE_PATH}/${portname}.log"
    elif [[ "${PW_VULKAN_USE}" = "2" ]] ; then
        echo "PW_VULKAN_USE=${PW_VULKAN_USE} - DXVK v.${DXVK_GIT_VER} and VKD3D-PROTON v.${VKD3D_GIT_VER}" >> "${PORT_WINE_PATH}/${portname}.log"
    elif [[ "${PW_VULKAN_USE}" = "3" ]] ; then
        echo "PW_VULKAN_USE=${PW_VULKAN_USE} - native DX9 on MESA drivers" >> "${PORT_WINE_PATH}/${portname}.log"
    elif [[ "${PW_VULKAN_USE}" = "4" ]] ; then
        echo "PW_VULKAN_USE=${PW_VULKAN_USE} - DirectX to wined3d vulkan" >> "${PORT_WINE_PATH}/${portname}.log"
    else
        echo "PW_VULKAN_USE=${PW_VULKAN_USE}" >> "${PORT_WINE_PATH}/${portname}.log"
    fi
    echo "--------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Version WINE in use:" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "$PW_WINE_USE" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Program bit depth:" >> "${PORT_WINE_PATH}/${portname}.log"
    if [[ $(file "$portwine_exe") =~ x86-64 ]]; then
        echo "64 bit" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-----------------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    else
        echo "32 bit" >> "${PORT_WINE_PATH}/${portname}.log"
    fi
    echo "--------------------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Date and time of start debug for ${portname}:" >> "${PORT_WINE_PATH}/${portname}.log"
    date >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-----------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "The installation path of the ${portname}:" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "$PORT_WINE_PATH" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "------------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Operating system:" >> "${PORT_WINE_PATH}/${portname}.log"
    cat /etc/os-release | grep -oP 'PRETTY_NAME="\K[^"]+' >> "${PORT_WINE_PATH}/${portname}.log"
    echo "--------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Desktop environment:" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Desktop session: ${DESKTOP_SESSION}" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Current desktop: ${XDG_CURRENT_DESKTOP}" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Session type: ${XDG_SESSION_TYPE}" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "---------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Kernel:" >> "${PORT_WINE_PATH}/${portname}.log"
    uname -r >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "CPU:" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "CPU physical cores:$(cat /proc/cpuinfo | grep 'cpu cores' | sort -u | cut -d':' -f2)" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "CPU logical cores: $(cat /proc/cpuinfo | grep 'processor' | wc -l)" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "CPU model name:$(cat /proc/cpuinfo | grep 'model name' | sort -u | cut -d':' -f2)" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "RAM:" >> "${PORT_WINE_PATH}/${portname}.log"
    free -m >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-----------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Graphic cards and drivers:" >> "${PORT_WINE_PATH}/${portname}.log"
    echo 'lspci -k | grep -EA3 VGA|3D|Display :' >> "${PORT_WINE_PATH}/${portname}.log"
    echo "$(lspci -k | grep -EA3 'VGA|3D|Display')" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "----" >> "${PORT_WINE_PATH}/${portname}.log"
    [[ `command -v glxinfo` ]] && glxinfo -B >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-----" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "inxi -G:" >> "${PORT_WINE_PATH}/${portname}.log"
    if ! check_flatpak
    then "${PW_PLUGINS_PATH}/portable/bin/inxi" -Gc0 >> "${PORT_WINE_PATH}/${portname}.log"
    fi
    if echo "$LSPCI_VGA" | grep -i nvidia &>/dev/null ; then
        if command -v ldconfig &>/dev/null ; then
            echo "------" >> "${PORT_WINE_PATH}/${portname}.log"
            echo "ldconfig -p | grep libGLX_nvidia" >> "${PORT_WINE_PATH}/${portname}.log"
            ldconfig -p | grep libGLX_nvidia >> "${PORT_WINE_PATH}/${portname}.log"
        fi
    fi
    echo "PW_SCREEN_RESOLUTION=$PW_SCREEN_RESOLUTION" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "PW_SCREEN_PRIMARY=$PW_SCREEN_PRIMARY" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "----------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "Vulkan info device name:" >> "${PORT_WINE_PATH}/${portname}.log"
    "$PW_VULKANINFO_PORTABLE" 2>/dev/null | grep -E '^GPU|deviceName|driverName' >> "${PORT_WINE_PATH}/${portname}.log"
    "${PW_PLUGINS_PATH}/portable/bin/vkcube" --c 50
    if [ $? -eq 0 ]; then
        echo "Vulkan cube test passed successfully" >> "${PORT_WINE_PATH}/${portname}.log"
    else
        echo "Vulkan cube test completed with error" >> "${PORT_WINE_PATH}/${portname}.log"
    fi
    echo "----------------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo 'locale:' >> "${PORT_WINE_PATH}/${portname}.log"
    locale >> "${PORT_WINE_PATH}/${portname}.log"
    echo "---" >> "${PORT_WINE_PATH}/${portname}.log"
    echo 'locale -a | grep -i "$(locale | grep -e '^LANG=' | sed 's/LANG=//' | sed  's/\-8//')" :' >> "${PORT_WINE_PATH}/${portname}.log"
    locale -a | grep -i "$(locale | grep -e '^LANG=' | sed 's/LANG=//' | sed  's/\-8//')" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    if [[ "${PW_USE_D3D_EXTRAS}" != 1 ]]
    then echo "D3D_EXTRAS - disabled" >> "${PORT_WINE_PATH}/${portname}.log"
    else echo "D3D_EXTRAS - enabled" >> "${PORT_WINE_PATH}/${portname}.log"
    fi
    echo "------------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    echo "winetricks.log:" >> "${PORT_WINE_PATH}/${portname}.log"
    cat "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" | sed -e /"^d3dcomp*"/d -e /"^d3dx*"/d >> "${PORT_WINE_PATH}/${portname}.log"
    echo "-----------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    if [ ! -z "${PORTWINE_DB_FILE}" ]; then
        echo "Use ${PORTWINE_DB_FILE} db file:" >> "${PORT_WINE_PATH}/${portname}.log"
        cat "${PORTWINE_DB_FILE}" | sed '/##/d' >> "${PORT_WINE_PATH}/${portname}.log"
    else
        echo "Use ${PORT_SCRIPTS_PATH}/portwine_db/default db file:" >> "${PORT_WINE_PATH}/${portname}.log"
        cat "${PORT_SCRIPTS_PATH}/portwine_db/default" | sed '/##/d' >> "${PORT_WINE_PATH}/${portname}.log"
    fi
    echo "----------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"
    if [ -f "${USER_CONF}" ]; then
        cat "${USER_CONF}" | sed '/bash/d' >> "${PORT_WINE_PATH}/${portname}.log"
    fi
    echo "---------------------------------------" >> "${PORT_WINE_PATH}/${portname}.log"

    export DXVK_HUD="full"

    portwine_launch &
    sleep 3
    pw_stop_progress_bar_cover
    unset PW_TIMER
    while read -r line || [[ ! -z $(pgrep -a yad | grep "yad_v13_0 --text-info --tail --button="STOP"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":0 --title="DEBUG"" | awk '{print $1}') ]] ; do
            sleep 0.005
            if [[ ! -z "${line}" ]] && [[ -z "$(echo "${line}" | grep -i "kerberos")" ]] \
                                    && [[ -z "$(echo "${line}" | grep -i "ntlm")" ]]
            then
                echo "# ${line}"
            fi
            if [[ "${PW_TIMER}" != 1 ]] ; then
                sleep 3
                PW_TIMER=1
            fi
    done < "${PORT_WINE_PATH}/${portname}.log" | "${pw_yad_v13_0}" --text-info --tail --button="STOP"!"$PW_GUI_ICON_PATH/$BUTTON_SIZE.png":0 --title="DEBUG" \
    --skip-taskbar --width=800 --height=400 --text "${port_debug}" --window-icon="$PW_GUI_ICON_PATH/portproton.svg" 2>/dev/null &&
    kill_portwine
    sed -i '/.fx$/d' "${PORT_WINE_PATH}/${portname}.log"
    sed -i '/HACK_does_openvr_work/d' "${PORT_WINE_PATH}/${portname}.log"
    sed -i '/Uploading is disabled/d' "${PORT_WINE_PATH}/${portname}.log"
    sed -i '/wine: RLIMIT_NICE is <= 20/d' "${PORT_WINE_PATH}/${portname}.log"
    sed -i '/ALT_2.24/d' "${PORT_WINE_PATH}/${portname}.log"
    sed -i '/UDEV monitor/d' "${PORT_WINE_PATH}/${portname}.log"
    deb_text=$(cat "${PORT_WINE_PATH}/${portname}.log"  | awk '! a[$0]++')
    echo "$deb_text" > "${PORT_WINE_PATH}/${portname}.log"
    "$pw_yad" --title="${portname}.log" --no-buttons --text-align=center \
    --text-info --show-uri --wrap --width=1200 --height=550  --uri-color=red \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" \
    --filename="${PORT_WINE_PATH}/${portname}.log"
    stop_portwine
}

pw_create_prefix_backup () {
    cd "$HOME"
    PW_PREFIX_TO_BACKUP=$("${pw_yad_v13_0}" --file --directory --width=650 --height=500 --auto-close \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --title "$loc_create_pfx_backup_path" 2>/dev/null )
    YAD_STATUS="$?"
    if [[ "$YAD_STATUS" == "1" || "$YAD_STATUS" == "252" ]] ; then exit 0 ; fi
    if [[ ! -z "$(grep "/${PW_PREFIX_NAME}/" "${PORT_WINE_PATH}"/*.desktop )" ]] ; then
        try_remove_file "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/.create_shortcut"
        grep "/${PW_PREFIX_NAME}/" "${PORT_WINE_PATH}"/*.desktop | awk -F"/${PW_PREFIX_NAME}/" '{print $2}' \
        | awk -F\" '{print $1}' > "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}/.create_shortcut"
    fi
    unset PW_SANDBOX_HOME_PATH
    export PW_ADD_TO_ARGS_IN_RUNTIME="--xterm"
    pw_init_runtime
    chmod -R u+w "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}"
    ${pw_runtime} env PATH="${PATH}" LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" mksquashfs "${PORT_WINE_PATH}/data/prefixes/${PW_PREFIX_NAME}" "${PW_PREFIX_TO_BACKUP}/${PW_PREFIX_NAME}.ppack.part" -comp zstd &
    sleep 10
    while true ; do
        if [[ ! -z $(pgrep -a xterm | grep ".ppack.part" | head -n 1 | awk '{print $1}') ]] ; then
            sleep 0.5
        else
            kill -TERM $(pgrep -a mksquashfs | grep ".ppack.part" | head -n 1 | awk '{print $1}')
            sleep 0.3
            if [[ -z "$(pgrep -a mksquashfs | grep ".ppack.part" | head -n 1 | awk '{print $1}')" ]]
            then break
            else sleep 0.3
            fi
        fi
    done
    if [[ -f "${PW_PREFIX_TO_BACKUP}/${PW_PREFIX_NAME}.ppack.part" ]] ; then
        mv -f "${PW_PREFIX_TO_BACKUP}/${PW_PREFIX_NAME}.ppack.part" "${PW_PREFIX_TO_BACKUP}/${PW_PREFIX_NAME}.ppack"
        yad_info "$PW_PFX_BACKUP_SUCCESS $PW_PREFIX_NAME"
        if [[ ! -f "${PORT_WINE_TMP_PATH}/pfx_backup_info" ]] ; then
            yad_info "$PW_PFX_BACKUP_INFO"
            echo "1" > "${PORT_WINE_TMP_PATH}/pfx_backup_info"
        fi
    else
        yad_error "$PW_PFX_BACKUP_ERROR $PW_PREFIX_NAME"
    fi

    return 0
}

pw_edit_db () {
    if [[ "${XDG_SESSION_TYPE}" == "wayland" ]] ; then
        pw_gui_for_edit_db \
        PW_MANGOHUD PW_MANGOHUD_USER_CONF ENABLE_VKBASALT PW_VKBASALT_USER_CONF PW_NO_ESYNC PW_NO_FSYNC PW_USE_RAY_TRACING \
        PW_USE_NVAPI_AND_DLSS PW_USE_FAKE_DLSS PW_USE_FAKE_DLSS_3 PW_WINE_FULLSCREEN_FSR PW_HIDE_NVIDIA_GPU PW_VIRTUAL_DESKTOP \
        PW_USE_TERMINAL PW_GUI_DISABLED_CS PW_USE_GAMEMODE PW_USE_D3D_EXTRAS PW_FIX_VIDEO_IN_GAME PW_REDUCE_PULSE_LATENCY \
        PW_USE_GSTREAMER PW_FORCE_LARGE_ADDRESS_AWARE PW_USE_SHADER_CACHE PW_USE_WINE_DXGI PW_USE_EAC_AND_BE PW_USE_SYSTEM_VK_LAYERS \
        PW_USE_OBS_VKCAPTURE PW_USE_GALLIUM_ZINK PW_USE_GAMESCOPE PW_DISABLE_COMPOSITING PW_USE_RUNTIME
    else
        pw_gui_for_edit_db \
        PW_MANGOHUD PW_MANGOHUD_USER_CONF ENABLE_VKBASALT PW_VKBASALT_USER_CONF PW_NO_ESYNC PW_NO_FSYNC PW_USE_RAY_TRACING \
        PW_USE_NVAPI_AND_DLSS PW_USE_FAKE_DLSS PW_USE_FAKE_DLSS_3 PW_WINE_FULLSCREEN_FSR PW_HIDE_NVIDIA_GPU PW_VIRTUAL_DESKTOP \
        PW_USE_TERMINAL PW_GUI_DISABLED_CS PW_USE_GAMEMODE PW_USE_D3D_EXTRAS PW_FIX_VIDEO_IN_GAME PW_REDUCE_PULSE_LATENCY\
        PW_USE_US_LAYOUT PW_USE_GSTREAMER PW_FORCE_LARGE_ADDRESS_AWARE PW_USE_SHADER_CACHE PW_USE_WINE_DXGI PW_USE_EAC_AND_BE \
        PW_USE_SYSTEM_VK_LAYERS PW_USE_OBS_VKCAPTURE PW_USE_GALLIUM_ZINK PW_USE_GAMESCOPE PW_DISABLE_COMPOSITING PW_USE_RUNTIME
    fi
    # PW_FORCE_USE_VSYNC HEAP_DELAY_FREE
}

pw_autoinstall_from_db () {
    export PW_USER_TEMP="${PORT_WINE_TMP_PATH}"
    export PW_FORCE_LARGE_ADDRESS_AWARE=1
    export PW_USE_GAMEMODE=0
    export PW_CHECK_AUTOINSTAL=1
    export PW_GUI_DISABLED_CS=1
    export PW_NO_WRITE_WATCH=0
    export PW_VULKAN_USE=1
    export PW_USE_EAC_AND_BE=0
    export PW_NO_FSYNC=1
    export PW_NO_ESYNC=1
    unset PORTWINE_CREATE_SHORTCUT_NAME
    export PW_DISABLED_CREATE_DB=1
    export PW_MANGOHUD=0
    export ENABLE_VKBASALT=0
    export PW_USE_D3D_EXTRAS=1
    . "${PORT_SCRIPTS_PATH}/pw_autoinstall/${PW_YAD_SET}"
}

gui_credits () {
    . "${PORT_SCRIPTS_PATH}/credits"
}
export -f gui_credits

button_click () {
    [[ ! -z "$1" ]] && echo "$1" > "${PORT_WINE_TMP_PATH}/tmp_yad_form"
    if [[ ! -z $(pidof -s yad) ]] || [[ ! -z $(pidof -s yad_v13_0) ]] ; then
        kill -s SIGUSR1 $(pgrep -a yad | grep "\--key=${KEY} \--notebook" | awk '{print $1}') > /dev/null 2>&1
    fi
}
export -f button_click

run_desktop_b_click () {
    [[ ! -z "$1" ]] && echo "$1" > "${PORT_WINE_TMP_PATH}/tmp_yad_form"
    if [[ ! -z $(pidof -s yad) ]] || [[ ! -z $(pidof -s yad_v13_0) ]] ; then
        kill -s SIGUSR1 $(pgrep -a yad | grep "\--key=${KEY} \--notebook" | awk '{print $1}') > /dev/null 2>&1
    fi

    if check_flatpak
    then PW_EXEC_FROM_DESKTOP="$(cat "${PORT_WINE_PATH}/${PW_YAD_SET//¬/" "}" | grep Exec | head -n 1 | sed 's|flatpak run ru.linux_gaming.PortProton|\"${PORT_SCRIPTS_PATH}/start.sh\"|' | awk -F'=' '{print $2}')"
    else PW_EXEC_FROM_DESKTOP="$(cat "${PORT_WINE_PATH}/${PW_YAD_SET//¬/" "}" | grep Exec | head -n 1 | awk -F"=env " '{print $2}')"
    fi

    print_info "Restarting PP after choose desktop file..."
    # stop_portwine
    export SKIP_CHECK_UPDATES=1
    /usr/bin/env bash -c "${PW_EXEC_FROM_DESKTOP}" &
    exit 0
}
export -f run_desktop_b_click

gui_clear_pfx () {
    if yad_question "${port_clear_pfx}" ; then
        pw_clear_pfx
        print_info "Restarting PP after clearing prefix..."
        export SKIP_CHECK_UPDATES=1
        /usr/bin/env bash -c ${pw_full_command_line[*]} &
        exit 0
    fi
}
export -f gui_clear_pfx

gui_rm_portproton () {
    if yad_question "${port_del2}" ; then
        rm -fr "${PORT_WINE_PATH}"
        rm -fr "${PORT_WINE_TMP_PATH}"
        rm -fr "${HOME}/PortWINE"
        rm -f $(grep -il PortProton "${HOME}/.local/share/applications"/*)
        update-desktop-database -q "${HOME}/.local/share/applications"
    fi
    exit 0
}
export -f gui_rm_portproton

gui_pw_update () {
    try_remove_file "${PORT_WINE_TMP_PATH}/scripts_update_notifier"
    print_info "Restarting PP for check update..."
    export SKIP_CHECK_UPDATES=1
    /usr/bin/env bash -c ${pw_full_command_line[*]} &
    exit 0
}

change_loc () {
    try_remove_file "${PORT_WINE_TMP_PATH}/${portname}_loc"
    print_info "Restarting PP for change language..."
    export SKIP_CHECK_UPDATES=1
    /usr/bin/env bash -c ${pw_full_command_line[*]} &
    exit 0
}

gui_wine_uninstaller () {
    start_portwine
    pw_run uninstaller
}
export -f gui_wine_uninstaller

gui_open_user_conf () {
    xdg-open "${PORT_WINE_PATH}/data/user.conf"
}
export -f gui_open_user_conf

gui_open_scripts_from_backup () {
    cd "${PORT_WINE_TMP_PATH}/scripts_backup/"
    PW_SCRIPT_FROM_BACKUP=$("${pw_yad_v13_0}" --file --width=650 --height=500 --auto-close \
    --window-icon="$PW_GUI_ICON_PATH/portproton.svg" --title "SCRIPTS FROM BACKUP" --file-filter="backup_scripts|scripts_v*.tar.gz" 2>/dev/null )
    YAD_STATUS="$?"
    if [[ "$YAD_STATUS" == "1" || "$YAD_STATUS" == "252" ]] ; then exit 0 ; fi
    unpack_tar_gz "$PW_SCRIPT_FROM_BACKUP" "${PORT_WINE_PATH}/data/"
    echo "0" > "${PORT_WINE_TMP_PATH}/scripts_update_notifier"
    print_info "Restarting PP after backup..."
    export SKIP_CHECK_UPDATES=1
    /usr/bin/env bash -c ${pw_full_command_line[*]} &
    exit 0
}
export -f gui_open_scripts_from_backup
