#!/bin/sh

# config data
exitnode=_exitemu
stdoutnode=_stdout

debug=true

# make sure we find our config directory
curdir="`pwd`"

pcemudir="`dirname $0`"
if [ "$pcemudir" = . ]; then
    if [ ! -f dosemu.conf ]; then
        echo "$0 must be started in pcemu dir or using explicit path name" \
	  1>&2
	exit 1
    else
        pcemudir="`pwd`"
    fi
else
    cd "$pcemudir"
    pcemudir="`pwd`"
fi

# make sure we've got a command to run
cmdline="$*"
if [ "x$cmdline" = x ]; then
    echo "${0}: no command to run" 1>&2
    exit 1
fi

# set up DOS runtime environment
relocdir="`dirname $pcemudir`/reloc"

rm -f "$relocdir"/* 2>/dev/null		# remove all flat files (not dirs)
#mkfifo "$relocdir/$exitnode"
#mkfifo "$relocdir/$stdoutnode"

# make command batch file
rm -f "$relocdir/autorun.bat"
( cat <<__FUNNY__
path e:\bin
c:\lredir f: LINUX\FS`echo $curdir | tr 'a-z/' 'A-Z\\\\'`
f:
$cmdline > e:$stdoutnode
@echo off
if errorlevel 1 goto error
echo 0 > e:$exitnode
goto ok
:error
echo 1 > e:$exitnode
:ok
c:exitemu
__FUNNY__
) | sed 's,$,
,' > "$relocdir/autorun.bat"

# run the emulator
/usr/bin/dos -F ./dosemu.conf  </dev/tty >/dev/null 2>&1 &
pcemupid=$!
sleep 1				# allow DOSEMU to initialize
stty cooked			# now switch the terminal back to
				# cooked mode to allow ^C

# wait for the emulator to exit
wait $pcemupid

code="`cat "$relocdir/$exitnode" | sed 's,
,,g'`"

# show stdout
cat "$relocdir/$stdoutnode"

trap 0 1 2 15
exit $code
