#!/bin/sh

# config data
exitnode=_exitemu
stdoutnode=_stdout

# sanity
if [ "x$DISPLAY" = x ]; then
    echo "${0}: DISPLAY not set; pcemu only works with X11" 1>&2
    exit 1
fi

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

pcemudir="`dirname $0`"
if [ "$pcemudir" = . ]; then
    if [ ! -f .pcemurc ]; 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

# generate config file if not already there
if [ ! -f .pcemurc ]; then
    if [ -f bootfloppy ]; then
        echo "${0}: generating $pcemudir/.pcemurc" 1>&2
	echo "bootfile $pcemudir/bootfloppy" > .pcemurc
	case "`du -k bootfloppy | cut -f1`" in
	144*) foo=144 ;;
	72*)  foo=720 ;;
	36*)  foo=360 ;;
	12*)  foo=12 ;;
	esac
	echo "boottype $foo" >> .pcemurc
    else
	echo "${0}: no .pcemurc and no bootfloppy, can't continue" 1>&2
	exit 1
    fi
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"

# make command batch file
rm -f "$relocdir/autorun.bat"
( cat <<__FUNNY__
path e:\bin
c:\lredir f: PCEMU\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
__FUNNY__
) | sed 's,$,
,' > "$relocdir/autorun.bat"

# run the emulator
pcemupid=0
trap "eval kill \$pcemupid; exit 1" 0 1 2 15
pcemu &
pcemupid=$!

# wait for the emulator to exit
read code < "$relocdir/$exitnode"

kill $pcemupid
wait $pcemupid

# show stdout
cat "$relocdir/$stdoutnode"

trap 0 1 2 15
exit $code
