#!/bin/bash
#
# Do Disk operations on relative disk numbers (i.e. disk 1) as opposed to 
# absolute disks (i.e. /dev/sdc )
#
# optparam prefix "-print-max" Print the maximum usable disk number
# optparam prefix "-print" value N: Print the devicename of disk N
# optparam prefix "-partition" value N Y: Make Y equal sized partitions on disk N
#

. /etc/autobench.conf || . functions

function print_usage() {
  echo "$0:"
  echo -e "\t -print-max"
  echo -e "\t   Print the maximum usable partition number"
  echo -e "\t -print N"
  echo -e "\t   Print the devicename of partition N"
  echo -e "\t -partition N Y"
  echo -e "\t   Make Y equal sized partitions on disk N"
  exit 1
}

if [ $# -lt 1 ]; then
  print_usage
fi

FREE_DISKS=`echo $DATS_FREE_DISKS | wc -w`

case $1 in
  -print-max)
    #Count the disks
    echo $FREE_DISKS
    ;;

  -print)
    if [ $# -lt 2 ]; then
      print_usage
    fi
    if [ $2 -gt $FREE_DISKS ]; then
      exit 6
    fi
    echo $DATS_FREE_DISKS | tr -s " " | cut -f$2 -d" "
    ;;

  -partition)
    if [ $# -lt 3 ]; then
      print_usage
    fi

    if [ $2 -gt $FREE_DISKS ]; then
      echo "Thare is not a ${2}th disk"
      exit 6
    fi

    DISK=`echo $DATS_FREE_DISKS | tr -s " " | cut -f$2 -d" "`

    # Even if we support 15 partitions, we need one for the extended table,
    # so >= 15...
    if [ $3 -ge 15 ]; then
      if [ -n "`echo $DISK | grep "sd"`" ]; then
        echo "Linux only supports 15 partitions on a SCSI disk"
        exit 4
      fi
      if [ $3 -ge 63 ]; then
        echo "Linux only supports 63 partitions on an IDE disk"
        exit 5
      fi
    fi

    TOTAL_SIZE=`sfdisk -l $DISK | grep "Disk $DISK" | tr -s " " | cut -d" " -f3`
    if [ $TOTAL_SIZE -lt $3 ]; then
      echo "Not enough space on device"
      exit 3
    fi

    OLDPARTS=`sfdisk -l $DISK | grep "^$DISK" | grep -v "Empty" | grep -v "Extended" | cut -f1 -d" "`
    for PART in $OLDPARTS; do
      umount -f $PART 2> /dev/null
    done
    
    NEW_SIZE=$(($TOTAL_SIZE/$3))
    for ((LOOP=1;LOOP<$3;LOOP++)); do
      NEW_CONFIG="${NEW_CONFIG},$NEW_SIZE\n"
      if [ $LOOP -eq 3 ]; then
        NEW_CONFIG="${NEW_CONFIG},,E\n"
      fi
    done
    NEW_CONFIG="${NEW_CONFIG},,\n\n"

    echo -e "$NEW_CONFIG" | sfdisk $DISK
    ;;

  *)
    print_usage
    ;;
esac
