#!/bin/bash
#
# Wrapper to dd(1): allow imageName:partition in if= and of= arguments
# 
# $Author: bablokb $
# $Revision: 1.2 $
#
# License: GPL2
# -----------------------------------------------------------------------------

. `dirname $0`/bxtfuncs.inc

# usage message   -------------------------------------------------------------

usage() {
  echo -e "\n`basename $0`: use dd with bochs-hd-image partitions\n\
  \nusage: `basename $0` [options] dd-arguments\n\
  possible options:\n\
    -V       show version\n\
    -h       show this help\n\
    -q       run quiet (default)\n\
    -v       verbose messages\n\
    -s       only simulate\n\
"
  exit 3
}

# set system defaults   -------------------------------------------------------

setDefaults() {
  quiet=1; simulate=0
  SEP=`echo x | tr x "\005"`
}

# parse arguments and set variables -------------------------------------------

parseArguments() {

  while getopts ":Vhqvs" opt; do
    case $opt in
      V) showCopyright `basename $0` "set the partition-type of a bochs-hd-image partition";;
      h) usage;;
      q) quiet=1;;
      v) quiet=0;;
      s) simulate=1;;
      ?) echo "error: illegal option: $OPTARG" >&2
           usage;;
    esac
  done
  shift $(( OPTIND-1 ))
  ddArgs="$@"
  [ $quiet -eq 0 ] && echo "ddArgs=$ddArgs" >&2
}

# check arguments   -----------------------------------------------------------

checkArguments() {
  :
}

# replace bochs-partition in dd-argument   ------------------------------------
#
# first argument is "if" or "of"

replaceDDArg() {
  local regexp="\(.*$1=\)\([^ ]*:[1-9][0-9]\?\)\(.*\)"
#                  \1            \2              \3
#                  ^             ^               ^- the rest
#                  |             |- hda.img:3 (second digit is optional)
#                  |- everything up to if= or of=
  if grep -q "$regexp" <<< $ddArgs; then
    image=`echo $ddArgs | sed -e "s$SEP$regexp$SEP\2$SEP"`
    [ $quiet -eq 0 ] && echo "image=$image" >&2
    if ! loopDevice=`setupLoopDevice $image`; then
      cleanupAndExit 1
    fi
    [ $quiet -eq 0 ] && echo "loop-device=$loopDevice" >&2
    ddArgs=`echo $ddArgs | sed -e "s$SEP$regexp$SEP\1$loopDevice\3$SEP"`
    [ $quiet -eq 0 ] && echo "ddArgs=$ddArgs" >&2
    eval ${1}Device="$loopDevice"
  fi
}

# cleanup and exit script   ---------------------------------------------------

cleanupAndExit() {
  if [ -n "$ifDevice" ]; then
    do_cmd "losetup -d $ifDevice"
  fi
  if [ -n "$ofDevice" ]; then
    do_cmd "losetup -d $ofDevice"
  fi
  exit $1
}

# main program   --------------------------------------------------------------

setDefaults
parseArguments "$@"
checkArguments
replaceDDArg "if"
replaceDDArg "of"
dd $ddArgs
cleanupAndExit 0
