#! /bin/bash
#	Copyright (c) 2013 Brocade Communications Systems, Inc.
#	All rights reserved.
#
#	Module name: mkfastmdt.sh
#
#	This program/script generate meta data of the supplied image.
#	Which is used by u-boot to load images faster into DDR from USB
#	Mass Storage
#
export PATH=/mnt/bin:/mnt/usr/bin:$PATH

if [ -z "$1" ];then
	echo "Usage : mkfastmdt.sh ImageName Address"
	exit
else
		filename=$1
fi

if [ -z "$2" ];then
	echo "Usage : mkfastmdt.sh ImageName Address"
	echo "Address missing"
	exit 1
else
	let addr=$2+0
fi

if [ ! -f $filename ]; then
	echo "File doesn't exists"
	exit 1
fi

#only use file name to make parsing faster
echo "[${filename##*/}]" > $filename.mdt

#process the segments
hdparm --fibmap $filename  > /tmp/fastbooting.txt
	
lines=`wc -l /tmp/fastbooting.txt | awk '{print $1}'`
i=5;
j=0;
k=0;
while [ $i -le $lines ];
do
	let j=i*-1
	data=`cat /tmp/fastbooting.txt | head $j | tail -1`
	s_LBA[$k]=`echo $data | awk '{print $2}'`
	e_LBA[$k]=`echo $data | awk '{print $3}'`
	let i=i+1
	let k=k+1
done
j=0;
lba1=${s_LBA[$j]}
lba2=${e_LBA[$j]}
while [ $j -lt $k ];
do
	let y=j+1
	x=${e_LBA[$j]}
	let x=x+1
	if [ $y -eq $k ];
	then
		let size=lba2-lba1
		let size=size+1
		addrh=`echo $addr | awk '{printf "0x%x", $1}'`
		lba1h=`echo $lba1 | awk '{printf "0x%x", $1}'`
		sizeh=`echo $size | awk '{printf "0x%x", $1}'`
		echo $addrh,$lba1h,$sizeh >> $filename.mdt
		break
	fi

	if [ $x -eq ${s_LBA[$y]} ];
	then
		lba2=${e_LBA[$y]}
	else
		let size=lba2-lba1
		let size=size+1
	
		addrh=`echo $addr | awk '{printf "0x%x", $1}'`
		lba1h=`echo $lba1 | awk '{printf "0x%x", $1}'`
		sizeh=`echo $size | awk '{printf "0x%x", $1}'`

		echo $addrh,$lba1h,$sizeh >> $filename.mdt
		let addr=addr+size*512
		lba1=${s_LBA[$y]}
		lba2=${e_LBA[$y]}
	fi

	let j=j+1

done

rm -rf /tmp/fastbooting.txt
exit 0
#EOF
