#!/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)
  # Example in FC5 with parted-1.7.1-15.fc5
  #[root@fc5101 tmp]# LC_ALL=C parted -s /dev/hda p
  #
  #Disk /dev/hda: 4295MB
  #Sector size (logical/physical): 512B/512B
  #Partition Table: msdos
  #
  #Number  Start   End     Size    Type     File system  Flags
  # 1      32.3kB  4285MB  4285MB  primary  ntfs         boot

  local DEV=$1
  local wanted=$2
  part_info_tmp=`mktemp /tmp/part_tmp.XXXXXX`
  LC_ALL=C parted -s $DEV p > $part_info_tmp
  # force to change the output temp file, no space in "File system"
  perl -pi -e "s/File system/Filesystem/g" $part_info_tmp
  for i in 1 2 3 4 5 6 7; do
    col="$(grep -i flags $part_info_tmp | awk -F" " "{print \$$i}")"
    if [ -n "$(echo $col | grep -i $wanted)" ]; then
      col_idx=$i
      break
    fi
  done
  [ -f "$part_info_tmp" ] && rm -f $part_info_tmp
  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)"
     [ -z "$start_idx" ] && exit 1
     part_start=$(grep -E "^[[:space:]]*$part_index\>" $part_info | awk -F" " "{print \$$start_idx}")
     echo "$part_start"
     ;;
  end)
     end_idx="$(check_col_idx $target_hd end)"
     [ -z "$end_idx" ] && exit 1
     part_end=$(grep -E "^[[:space:]]*$part_index\>" $part_info | awk -F" " "{print \$$end_idx}")
     echo "$part_end"
     ;;
  size)
     size_idx="$(check_col_idx $target_hd size)"
     [ -z "$size_idx" ] && exit 1
     part_size=$(grep -E "^[[:space:]]*$part_index\>" $part_info | awk -F" " "{print \$$size_idx}")
     echo "$part_size"
     ;;
  type)
     type_idx="$(check_col_idx $target_hd type)"
     [ -z "$type_idx" ] && exit 1
     part_type=$(grep -E "^[[:space:]]*$part_index\>" $part_info | awk -F" " "{print \$$type_idx}")
     echo "$part_type"
     ;;
  filesystem)
     filesystem_idx="$(check_col_idx $target_hd file)"
     [ -z "$filesystem_idx" ] && exit 1
     part_fs=$(grep -E "^[[:space:]]*$part_index\>" $part_info | awk -F" " "{print \$$filesystem_idx}")
     echo "$part_fs"
     ;;
  flags)
     flags_idx="$(check_col_idx $target_hd flags)"
     [ -z "$flags_idx" ] && exit 1
     part_flags=$(grep -E "^[[:space:]]*$part_index\>" $part_info | awk -F" " "{print \$$flags_idx}")
     echo "$part_flags"
     ;;
esac

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