#!/bin/sh
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL

LC_ALL=C
# part is like /dev/hda1
# wanted is one of start, end, size, type, filesystem or flags.
part="$1"
wanted="$2"

[ -z "$part" -o -z "$wanted" ] && exit 1

p="$(basename $part)"
target_hd="/dev/${p:0:3}"
part_index="${p:3}"

check_col_idx() {
  # DEV is like /dev/hda
  # wanted is like "start", "end", "file" (since it's "file system" in SuSE 10.0, and filesystem in Redhat/FC)
  local DEV=$1
  local wanted=$2
  part_info=`mktemp /tmp/part.XXXXXX`
  LC_ALL=C parted -s $DEV p > $part_info
  for i in 1 2 3 4 5 6 7; do
    col="$(grep -i flags $part_info | awk -F" " "{print \$$i}")"
    if [ -n "$(echo $col | grep -i $wanted)" ]; then
      col_idx=$i
      break
    fi
  done
  [ -f "$part_info" ] && rm -f $part_info
  echo $col_idx
}

part_info=`mktemp /tmp/part.XXXXXX`
LC_ALL=C parted -s $target_hd p > $part_info

case "$wanted" in
  start)
     start_idx="$(check_col_idx $target_hd start)"
     part_start=$(grep "^$part_index" $part_info | awk -F" " "{print \$$start_idx}")
     echo "$part_start"
     ;;
  end)
     end_idx="$(check_col_idx $target_hd end)"
     part_end=$(grep "^$part_index" $part_info | awk -F" " "{print \$$end_idx}")
     echo "$part_end"
     ;;
  size)
     size_idx="$(check_col_idx $target_hd size)"
     part_size=$(grep "^$part_index" $part_info | awk -F" " "{print \$$size_idx}")
     echo "$part_size"
     ;;
  type)
     type_idx="$(check_col_idx $target_hd type)"
     part_type=$(grep "^$part_index" $part_info | awk -F" " "{print \$$type_idx}")
     echo "$part_type"
     ;;
  filesystem)
     filesystem_idx="$(check_col_idx $target_hd file)"
     part_fs=$(grep "^$part_index" $part_info | awk -F" " "{print \$$filesystem_idx}")
     echo "$part_fs"
     ;;
  flags)
     flags_idx="$(check_col_idx $target_hd flags)"
     part_flags=$(grep "^$part_index" $part_info | awk -F" " "{print \$$flags_idx}")
     echo "$part_flags"
     ;;
esac

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