#!/bin/sh
# Written by Steven Shiau <steven@nchc.org.tw> to use in DRBL for RedHat
# License: GPL
#
# To solve the small partition image restore to larger partition problem.
#

target_hd="$1"
DEST_PART="$2"

Usage() {
    echo "Usage: `basename $0` harddrive partition"
    echo "Example: `basename $0` hda 1"
}

# check if the user input /dev/hda, /dev/hdb...
check_input_hd() {
    local target_hd="$1"
    case "$target_hd" in
	 [hs]d[a-z])
	   continue
	   ;;
	 *)
	  echo "Unknown HD device! Program stop!"
          Usage
	  exit 1
    esac
}

#
[ $# -ne 2 ] && Usage && exit 1

#
check_input_hd $target_hd

#
case "$DEST_PART" in
    [1-9])
             continue
             ;;
    [0-9][0-9])
             continue
             ;;
        *)
             Usage
             exit 1
esac

target_hd="/dev/$target_hd"
part_info=`mktemp /tmp/part.XXXXXX`

#output example
#Disk geometry for /dev/hda: 0.000-1536.000 megabytes
#Disk label type: msdos
#Minor    Start       End     Type      Filesystem  Flags
#1          0.031   1240.312  primary   reiserfs    
#4       1355.977   1535.625  extended              
#5       1356.007   1535.625  logical               
#Information: Don't forget to update /etc/fstab, if necessary.

/sbin/parted $target_hd p > $part_info

partition="${target_hd}${DEST_PART}"

# check partition
[ -z "`grep "^$DEST_PART" $part_info`" ] && echo "No such partition ($partition) exists! Program stop!" && exit 1
[ -n "`grep "^$partition" /proc/mounts`" ] && echo "Partition $partition is already mounted! You must unmount it first! Program stop!" && exit 1

part_start=$(grep "^$DEST_PART" $part_info | awk -F" " '{print $2}')
part_end=$(grep "^$DEST_PART" $part_info | awk -F" " '{print $3}')
part_fs=$(grep "^$DEST_PART" $part_info | awk -F" " '{print $5}')

echo "start_size end_size (megabytes) filesystem: $part_start $part_end $part_fs"

case "$part_fs" in
   reiserfs)
              echo "/sbin/resize_reiserfs ${partition}"
              /sbin/resize_reiserfs ${partition}
              ;;
   vfat|fat16|fat32)
              #  resize MINOR START END
              echo "/sbin/parted $target_hd resize $DEST_PART $part_start $part_end"
              /sbin/parted $target_hd resize $DEST_PART $part_start $part_end
              ;;
   ext2|ext3)
              echo "/sbin/e2fsck -f ${partition}; /sbin/resize2fs ${partition}"
              /sbin/e2fsck -f ${partition}
              /sbin/resize2fs ${partition}
              ;;
        *)
	      echo "Unknown filesystem...Program stop!"
	      exit 1
esac

[ -f "$part_info" ] && rm -f $part_info
