#! /bin/bash

do_wine()
{
    test -n "$cmd" && exec $cmd "$@"
    echo "$WINEPREFIX"
    exit 0
}

dir=`pwd`
cmd="wine"

case "X$1" in
    X*.exe|X*.EXE|X--help|X--version)
	;;
    X-k|X--kill|X-w|X--wait)
	cmd="wineserver"
	;;
    X-c|X--config)
	cmd="winecfg"
	shift
	;;
    X-b|X--boot)
	cmd="wineboot"
	shift
	;;
    X-u|X--update)
	cmd="wineboot"
	;;
    X-t|X--tricks)
	cmd="winetricks"
	shift
	;;
    X-h)
	cmd="$cmd --help"
	shift
	;;
    X-v)
	cmd="$cmd --version"
	shift
	;;
    X-s)
	cmd="$cmd explorer /desktop=${2},${2}"
	shift
	shift
	;;
    X--size=*)
	cmd="$cmd explorer /desktop=${1#*=},${1#*=}"
	shift
	;;
    X-i|X--info)
	cmd=`which wine`
	if [ -n "$cmd" ]; then
	    echo -n `$cmd --version`" in $cmd using "
	    cmd=""
	fi
	;;
    X-l)
	exec >> "${2}" 2>&1
	shift
	shift
	;;
    X--log=*)
	exec >> "${1#*=}" 2>&1
	shift
	;;
    X-*)
	echo "Unknown option: $1" >&2
	exit 1
	;;
    Xwine*)
	cmd="$1"
	shift
	;;
    X)
	cmd=""
	;;
esac

while test -n "$dir"; do
    if [ -d "$dir/dosdevices" -a -s "$dir/system.reg" ]; then
	export WINEPREFIX="$dir"
	do_wine "$@"
    fi
    if [ -f "$dir/.wine" ]; then
	pre=`cat "$dir/.wine"` 2>/dev/null
	if [ -d "$pre/dosdevices" -a -s "$pre/system.reg" ]; then
	    export WINEPREFIX="$pre"
	    do_wine "$@"
	fi
    fi
    if [ -h "$dir/.wine" ]; then
	pre=`readlink -f "$dir/.wine"` 2>/dev/null
	if [ -d "$pre/dosdevices" -a -s "$pre/system.reg" ]; then
	    export WINEPREFIX="$pre"
	    do_wine "$@"
	fi
    fi
    dir="${dir%/*}"
done

do_wine "$@"
