#!/bin/bash -x
#
# (c) 2009,2010 Instituto Superior Técnico
#
# License: GPL-2
#



LBA=$1
DEV=$2
export PART

T=`mktemp`
TO=`mktemp`
#function findpartition () 
fdisk -lu $DEV | egrep "^/" > $T

# for (( i = `wc -l < $T` ; i > 0 ; i -- )) ; do
#     echo $i
#     head -n $i $T | tail -n 1 | read -a array
#     #read part beg end size type
#     #echo $part $beg $end $size $type
#     echo ${array[*]}
# done

cat $T | while read part beg end size type  last; do
    if test $1 -le $end -a $1 -ge $beg; then
	echo $part > $TO
	echo $beg >> $TO
	echo $end >> $TO
	echo $size >> $TO
	echo $type >> $TO
    fi
done
cat $TO
PART=`head -n 1 $TO`
BEG=`head -n 2 $TO| tail -n 1`
TYPE=`head -n 5 $TO | tail -n 1`

echo $PART $BEG $TYPE

file -sk $PART
BLOCK=$(( (LBA - BEG)*512/4096))
echo $BLOCK

case `file -sk $PART` in
    *Linux*ext3\ filesystem*)
	echo "Linux"
	debugfs -R "testb $BLOCK" $PART | tee $TO
	if grep "not in use" $TO; then
	    echo "Block on Free Space"
	else
	    debugfs -R "icheck $BLOCK" $PART | tee $TO
	    INODE=`grep $BLOCK $TO | cut -f 2`
	    debugfs -R "ncheck $INODE" $PART
	fi
	;;
    *swap\ file*)
	echo "Swap"
	;;
    *LVM2*)
	echo "LVM"
	VG=`pvdisplay -c $PART | cut -d: -f2`
	PESIZE=`pvdisplay -c $PART | cut -d: -f 8`
	grep -A5 $PART /etc/lvm/backup/$VG
	PENUMBER=$(( BLOCK / PESIZE / 2))
	echo $PENUMBER
	pvdisplay -m $PART | grep "Physical extent"  | cat -n | while read nlinha word1 word2 begin to end2 last ; do
	    echo $nlinha $word1 $word2 $begin $to $end2 $last
	    end=${end2%%:}
	    if test $PENUMBER -ge $begin -a $PENUMBER -le $end ; then
		pvdisplay -m $PART | grep -A1 "Physical extent" | head -n $(( nlinha * 2 )) | tail -n 1 > $TO
	    fi
	done
	cut -f 2 $TO
	;;
    *)
	echo "Outro tipo"
esac

#cat $T

