#! /bin/bash
#
# (C) 1997 under GPL, Hans Lermen <lermen@fgan.de>
#
# Execute the any mtools command with a temporary MTOOLSRC, so we need
# not to fiddle with the user's configuration and are always doing right;-)
#
# NOTE: You need mtools >= 3.6 for this to work.
#

function usage {
  echo "USAGE:"
  echo "  do_mtools device mcommand [ arg1 [...] ]"
  echo ""
  echo "where is:"
  echo "  device    = DOS-partition such as '/dev/hda1'"
  echo "              or a DOSEMU hdimage"
  echo "  mcommand  = any valid mtools comand"
  echo "  argX      = any valid mtools argument."
  echo "              NOTE: for the DOS drive use 'W:'"
  echo ""
  echo "example:"
  echo "  do_mtools /var/lib/dosemu/hdimage mcopy W:/autoexec.bat -"
  exit 1
}

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 {
  xxMAGIC=`dd if=$1 bs=5 count=1 2>/dev/null`
  xxDEX=`echo -e "\016DEXE"`
  if [ "$xxMAGIC" = "DOSEM" -o "$xxMAGIC" = "$xxDEX" ]; 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="$*"
  mkdir -p ~/.dosemu/tmp
  tmprc=~/.dosemu/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 "$@"
  myerrcode=$?
  rm -f $tmprc
  return $myerrcode
}

if [ -z $2 ]; then
  usage
fi

do_mtool "$@"
exit $myerrcode
