# Discover the architecture of an existing prefix. Registries created by older
# 32-bit Wine versions may have no architecture marker.
wine_prefix_arch()
{
    if [ -n "$1" ] && [ -r "$1/system.reg" ]; then
        wine_registry_arch=$(sed -n '/^[[:space:]]*\[/q; /^[[:space:]]*#arch=/{s/^[[:space:]]*#arch=//;s/[[:space:]]*$//;p;q;}' "$1/system.reg")
        printf '%s\n' "${wine_registry_arch:-win32}"
    fi
}

# Both the launcher and the server must use the same implicit prefix.
select_wine_backend()
{
    wine_backend=
    wine_prefix=${WINEPREFIX:-${HOME:+$HOME/.wine}}
    wine_arch=$(wine_prefix_arch "$wine_prefix")
    if [ -z "$WINEPREFIX" ] && [ -n "$HOME" ] && [ -x "$1" ] &&
       [ "$wine_arch" != win32 ] &&
       { [ "$WINEARCH" = win32 ] || [ ! -x "$2" ]; }; then
        wine_prefix=$HOME/.wine32
        export WINEPREFIX="$wine_prefix"
        wine_arch=$(wine_prefix_arch "$wine_prefix")
    fi

    wine_arch=${wine_arch:-$WINEARCH}
    if [ -x "$1" ] && { [ "$wine_arch" = win32 ] || [ ! -x "$2" ]; }; then
        wine_backend=$1
        if [ -n "$wine_prefix" ]; then
            export WINEPREFIX="$wine_prefix"
        fi
    elif [ -x "$2" ]; then
        wine_backend=$2
    fi
}
