#!/bin/sh
# mkclean
# Cleaning TARGET and MEDIA, but ... NOT the DISTRO directory
# Must be exported first
#   MEDIA_DEV, MEDIA, TARGET_DEV, TARGET  
#

FORMAT="mkreiserfs -f"
#FORMAT="mke2fs -F"

error_exit() {
    echo "ERROR: $1"
    exit 1
}

get_input() { 
  local output
  if [ "`echo $BASH_VERSION | cut -b1`" = "1" ]; then
    echo -n "${1} " >&2 # fudge for use with bash v1
    read output
  else # this should work with any other /bin/sh
    read -ep "${1} " output
  fi
  echo $output
}

# clean_mnt MOUNT DEVICE
clean_mnt() {
  vcmount $1 $2 || exit 1
  ls $1
   reply=`get_input "Clean $1 [$2] ? Y/N"`
   if [ "$reply" != "Y" ] && [ $reply != "y" ]; then
      return 0
   fi
   if [ "$2" ]; then
     echo "Formating $TARGET ..."
     umount $2 || error_exit "cannot umount $2"
     $FORMAT $2 || error_exit "cannot format $2"
     mount $2 $1
   else
     echo "Deleting $1/*"
     rm -rf $1/*
   fi
}

case $1 in
  target)
    echo "Cleaning TARGET"
    [ -z "$TARGET" ] && error_exit "no TARGET"
    clean_mnt $TARGET $TARGET_DEV
    ;;
  media)
    echo "Cleaning MEDIA"
    [ -z "$MEDIA" ] && error_exit "no MEDIA"
    clean_mnt $MEDIA $MEDIA_DEV
    ;;
  *)
    [ -z "$MEDIA" ] && error_exit "no MEDIA"
    [ -z "$TARGET" ] && error_exit "no TARGET"
    echo "Cleaning TARGET"
    clean_mnt $TARGET $TARGET_DEV
    echo
    echo "Cleaning MEDIA"
    clean_mnt $MEDIA $MEDIA_DEV
esac
