#!/bin/sh
#
# wine	Allow users to run Windows(tm) applications by just clicking on them
#	(or typing ./file.exe)
#
# chkconfig: - 99 01
# description:	Allow users to run Windows(tm) applications by just clicking \
#		on them (or typing ./file.exe)
# processname: wine

OUTFORMAT=/etc/init.d/outformat
[ -x $OUTFORMAT ] || OUTFORMAT=/etc/init.d/wine.outformat

if which tput >/dev/null && test -x $OUTFORMAT ; then
	. $OUTFORMAT
else
	MOVE_TO_COL(){ :; }
	SETCOLOR_SUCCESS(){ :; }
	SETCOLOR_FAILURE(){ :; }
	SETCOLOR_WARNING(){ :; }
	SETCOLOR_NORMAL(){ :; }
fi

success()
{
	MOVE_TO_COL
	echo -n '[ '
	SETCOLOR_SUCCESS
	echo -n 'DONE'
	SETCOLOR_NORMAL
	echo -e ' ]\r'
}

failure()
{
	MOVE_TO_COL
	echo -n '['
	SETCOLOR_FAILURE
	echo -n 'FAILED'
	SETCOLOR_NORMAL
	echo -e ']\r'
}

passed()
{
	MOVE_TO_COL
	echo -n '['
	SETCOLOR_WARNING
	echo -n 'PASSED'
	SETCOLOR_NORMAL
	echo -e ']\r'
}

RETVAL=0

PROCBIN=/proc/sys/fs/binfmt_misc

check()
{
	[ -e $PROCBIN/windows -o -e $PROCBIN/windowsPE ]
}

start()
{
    if check ; then
		echo -n "WINE: Binary handler for Windows programs already registered. "
		passed
		return
    fi
	echo -n "WINE: Registering binary handler for Windows programs: "
	/sbin/modprobe binfmt_misc 2>/dev/null
	mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc 2>/dev/null
	[ -e $PROCBIN/register ] || { failure ; return 1; }
	echo ':windows:M::MZ::/usr/bin/wine:' >$PROCBIN/register &&
	echo ':windowsPE:M::PE::/usr/bin/wine:' >$PROCBIN/register &&
	success || failure
}

stop()
{
	echo -n "WINE: Unregistering binary handler for Windows programs: "
        check || { passed ; return 1 ; }
        echo '-1' >$PROCBIN/windows &&
        echo '-1' >$PROCBIN/windowsPE &&
        success || failure
}

status()
{
	if  check ; then
		echo "Wine binary format handlers are registered."
		return 0
	else
		echo "Wine binary format handlers are not registered."
		return 3
	fi
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	condstop)
	        check && stop
	        ;;
	condrestart|try-restart)
		check && stop && start
		;;
	status)
		status
		;;
	*)
		echo "${0##*/} {start|stop|restart|condstop|condrestart|status}" >&2
		false
esac

