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

. `dirname $0`/bxtfuncs.inc

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

usage() {
  echo -e "\n`basename $0`: copy a dir-tree to a partition of a bochs-hd-image\n\
  \nusage: `basename $0` [options] source-dir image-name:partition\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=""
}

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

parseArguments() {

  while getopts ":x:Vhqvs" opt; do
    case $opt in
      x) extraOptions=$OPTARG;;
      V) showCopyright \
         `basename $0` "copy a dir-tree to 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 source-dir image-name:partition" >&2
    usage
  elif [ $# -eq $OPTIND ]; then
    echo "error: missing argument image-name:partition" >&2
    usage
  fi
  
  sourceDir=${!OPTIND}
  let OPTIND+=1
  
  if [ $# -eq $OPTIND ]; then
    targetPartition=${!OPTIND}
  else
    echo "error: illegal argument ${!#}" >&2
    usage
  fi
}

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

checkArguments() {
  if [ ! -d $sourceDir ]; then
    echo "error: source-dir $sourceDir does not exist!" >&2
    exit 1
  fi
}

# copy using tar   ------------------------------------------------------------

doCopy() {
  if ! do_cmd "tar -cpf - -C $sourceDir . | tar -xpf - -C $mountPoint"; then
    echo "error: copy failed!" >&2
    exit 1
  fi
}
  
# main program   --------------------------------------------------------------

setDefaults
parseArguments "$@"
checkArguments
createMountPoint mountPoint ||  exit 1
if ! doMount $targetPartition $mountPoint; then
  do_cmd "rm -fr $mountPoint"
  echo "error: mount of $targetPartition failed!" >&2
  exit 1
fi
doCopy
doUmount $mountPoint
exit 0