#!/bin/bash
#
# Mount a partition of a bochs disk-image.
# 
# $Author: bablokb $
# $Revision: 1.9 $
#
# License: GPL2
# -----------------------------------------------------------------------------

. `dirname $0`/bxtfuncs.inc
pgmDir=`dirname $0`

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

usage() {
  echo -e "\n`basename $0`: mount a partition of a bochs-hd-image\n\
  \nusage: `basename $0` [options] image-name:partition mount-point\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\
    -x opts  pass extra options to mount (opts must be quoted)\n\
"
  exit 3
}

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

setDefaults() {
  quiet=1; simulate=0;
  extraOptions=""
  partition=""
}

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

parseArguments() {

  while getopts ":x:Vhqvs" opt; do
    case $opt in
      x) extraOptions=$OPTARG;;
      V) showCopyright `basename $0` "mount a partition of a bochs-hd-image";;
      h) usage;;
      q) quiet=1;;
      v) quiet=0;;
      s) simulate=1;;
      ?) echo "error: illegal option: $OPTARG" >&2
           usage;;
    esac
  done
  if [ $# -lt $OPTIND ]; then
    echo "error: missing arguments image-name:partition mount-point" >&2
    usage
  elif [ $# -eq $OPTIND ]; then
    echo "error: missing argument mount-point" >&2
    usage
  fi
  
  imageName=${!OPTIND%:*}
  partition=${!OPTIND#*:}
  let OPTIND+=1
  
  if [ $# -eq $OPTIND ]; then
    mountPoint=${!OPTIND}
  else
    echo "error: illegal argument ${!#}" >&2
    usage
  fi
}

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

checkArguments() {
  if [ ! -f $imageName ]; then
    echo "error: image $imageName does not exist!" >&2
    exit 1
  fi
  if [ -z $partition ]; then
    echo "error: no partition number specified!" >&2
    exit 1
  fi
  if [ ! -d $mountPoint ]; then
    echo "error: mount point $mountPoint does not exist!" >&2
    exit 1
  fi
}

# mount partition using loop device   -----------------------------------------

mountPartition() {
  local offset=$1

  if [ -z $offset ]; then
    echo "error: partition $partition does not exist!" >&2
    exit 1
  elif [ $offset -eq 0 ]; then
    echo "error: partition $partition does not exist!" >&2
    exit 1
  fi

  if ! do_cmd "mount -o loop,offset=$offset $extraOptions $imageName $mountPoint";
    then
      echo "error: could not mount $imageName:partition on $mountPoint" >&2
      exit 1
  fi

}

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

setDefaults
parseArguments "$@"
checkArguments
setGeometry $imageName
mountPartition `"$pgmDir"/bxtptinfo -p $partition $imageName`
exit 0