#!/bin/sh

# config data
stdoutnode=_stdout
tmpfile=tmp.stdout.$$

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

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

# sanity
if [ ! -f spcconfig.tmpl ]; then
    echo "${0}: no spcconfig.tmpl, can't continue" 1>&2
    exit 1
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"

for i in autorun.bat reloc; do
    if [ -s "$curdir/$i" ]; then
        echo "${0}: can't create $i in ${curdir}: already exists" 1>&2
        exit 1
    fi
done

trap "rm -f $curdir/reloc $curdir/autorun.bat; exit 1" 0 1 2 15

ln -s "$relocdir" "$curdir/reloc"

# make command batch file
( cat <<__FUNNY__
set PATH=e:\reloc\bin;%PATH%
$cmdline > e:\reloc\\$stdoutnode
@echo off
if not errorlevel 1 goto ok
echo __xxFINISH1xx__
goto exit
:ok
echo __xxFINISH0xx__
:exit
__FUNNY__
) | sed 's,$,
,' > "$curdir/autorun.bat"

if [ -f $HOME/.spcconfig ]; then
    mv $HOME/.spcconfig $HOME/.spcconfig.save
    trap "rm -f $curdir/reloc $curdir/autorun.bat; cp -fp $HOME/.spcconfig.save $HOME/.spcconfig; exit 1" 0 1 2 15
fi

sed "s,@DRIVE_E_DIR@,${curdir}," spcconfig.tmpl > $HOME/.spcconfig

# run the emulator
expect -f rundos.e
code=$?

trap "rm -f $curdir/reloc $curdir/autorun.bat; exit 1" 0 1 2 15

if [ -f $HOME/.spcconfig.save ]; then
    cp -fp $HOME/.spcconfig.save $HOME/.spcconfig
fi

# show stdout
[ -f "$relocdir/$stdoutnode" ] && cat "$relocdir/$stdoutnode"
rm -f $curdir/reloc $curdir/autorun.bat

trap 0 1 2 15

exit $code
