#! /bin/bash
#
# (C) 1997 under GPL, Hans Lermen <lermen@fgan.de>
#
# Execute a direct executable (bootable) *.dexe hdimage
#
# NOTE: You need mtools >= 3.6 for this to work.
#


DPATH=/var/lib/dosemu

function usage {
  echo 'USAGE:'
  echo '  dosexec dexe-file'
  exit 1
}

if [ -z $1 ]; then
  usage
fi

DEXE=$1
shift

if [ "$(( `mtools -V|awk '{print $3}'|tr ',a-z' ' '|tr '.' '0'` < 306 ))" \
      = "1" ]; then
  echo "wrong mtools version installed, please upgrade to >= 3.6"
  exit 1
fi

function is_hdimage {
  if [ "DOSEMU" = "`dd if=$1 bs=6 count=1 2>/dev/null`" ]; then
    return 0
  fi
  return 1
}

function do_mtool {
# $1  = device or hdimage
# $2  = mtools command
# $.. = rest of command line
# use 'W:' to access the dos drive
  device=$1
  mcommand=$2
  shift; shift
  params="$*"
  tmprc="/tmp/mtoolrc.$$"
  partition=""
  offset=""
  if is_hdimage $device; then
    partition="partition=1"
    offset="offset=128"
  fi
cat > $tmprc <<EOF
drive w: file="$device" MTOOLS_SKIP_CHECK=1 MTOOLS_LOWER_CASE=1 mtools_no_vfat=1 $partition $offset
EOF
  MTOOLSRC="$tmprc"
  export MTOOLSRC
  $mcommand $params
  rm -f $tmprc
}

if [ ! -f $DEXE ]; then
  DEXE="${DPATH}/${DEXE}"
  if [ ! -f $DEXE ]; then
    echo "$DEXE does not exist"
    exit 1
  fi
fi

if ! is_hdimage $DEXE; then
  echo "$DEXE is not a hdimage"
  exit 1
fi

TMP="/tmp/dexe.$$"
mkdir -p $TMP

do_mtool $DEXE mcopy W:/dconfig ${TMP}

#less ${TMP}/dconfig
dos $* -F ${TMP}/dconfig -I "disk { image \"$DEXE\" }"

rm -rf $TMP
