#!/bin/bash
set +x
function processor ()
{
	if [ -f $1 ]; then
		echo md5sum generate and check
		md5sum $1 > $1.md5.txt
		md5sum -c $1.md5.txt
		if [ -f $1-pcba ]; then
			md5sum $1-pcba > $1-pcba.md5.txt
			md5sum -c $1-pcba.md5.txt
		fi
		if [ "$3" = "LS3C5000-Dual-C6" ]; then
			if [ -f gen-image-tar ]; then
				echo run c6 gen-image-tar
				./gen-image-tar -t bios -m loongson-la2k500-mini-1v3 -v $2 $1
				if [ -f obmc-bios.tar.gz ]; then
					echo rename obmc-bios-2k500.tar.gz
					mv obmc-bios.tar.gz obmc-bios-2k500.tar.gz
					if [ -f obmc-bios-2k500.tar.gz ]; then
						md5sum obmc-bios-2k500.tar.gz > obmc-bios-2k500.tar.gz.md5.txt
						md5sum -c obmc-bios-2k500.tar.gz.md5.txt
					fi
				fi
                           ./gen-image-tar -t bios -m loongson-ast2500 -v $2 $1
			fi
		else
			if [ -f gen-image-tar ]; then
				echo run gen-image-tar
				./gen-image-tar -t bios -m loongson-ast2500 -v $2 $1
			fi
		fi
		if [ -f obmc-bios.tar.gz ]; then
			md5sum obmc-bios.tar.gz > obmc-bios.tar.gz.md5.txt
			md5sum -c obmc-bios.tar.gz.md5.txt
		fi
	fi
}

function cleanup()
{
	files=$(find $root_dir -name "*md5.txt" | sed 's#.*/##')
	echo $files
	for filename in $files
	do
		find $root_dir -name $filename -type f | while read temp_file;
		do
			echo $temp_file; 
			rm $temp_file
			echo remove $filename ok; 
		done
	done

	files=$(find $root_dir -name "*.tar.gz" | sed 's#.*/##')
	echo $files
	for filename in $files
	do
		find $root_dir -name $filename -type f | while read temp_file;
		do
			echo $temp_file; 
			rm $temp_file
			echo remove $filename ok; 
		done
	done
}

root_dir=$PWD
support_board=(LS3C5000-Dual LS3C5000-Dual-C6 LS3C5000L-Dual)
pkt_path=$(cd `dirname $0`; pwd)
pkt_name="${pkt_path##*/}"
echo $pkt_path
echo $pkt_name
vers=V4.0.

if [ $1 ];then

	if [ $1 == "clean" ]; then
		cleanup
		exit 1
	fi
	for var in ${support_board[@]};
	do
		echo $var
		files=$(find $root_dir/$var -name "*.fd.enc" | sed 's#.*/##')
		echo $files
		cd $var
		echo $vers$1
		processor $files $vers$1 $var
		cd -
		sleep 1
	done
	tar -czvf ../$pkt_name.tgz *
fi

set -x
