#!/bin/sh
# Copyright (c) 2000-2007 Synology Inc. All rights reserved.
DO_TAR="Y"
ADD_SELF_CKSUM="Y"

Usage()
{
	cat << EOF
Usage:
	`basename $0` [-Ch] [-P|-p patch_name.pat] filenames

	This script will generate a checksum.syno file which contains cksum of
	all @a filenames, and then archive them into @a patch_name.pat.

	Options:
	-C: Do not calculate cksum of the checksum.syno itself.
	-P: Skip Tar action; that is, generate checksum.syno only.
	-h: Usage.
EOF
}

CurDir=`pwd`
cd $CurDir

cd `dirname $0`
ScriptsDir=`pwd`
cd $CurDir

while getopts "CPhp:" opt ; do
case "$opt" in
	C) ADD_SELF_CKSUM="N";;
	P) DO_TAR="N";;
	p)
		if [ ${DO_TAR} = "N" ]; then
			echo "Warning: Assign the patch filename, but skip tar action."
			DO_TAR="Y"
		fi
		PATCH_NAME="${OPTARG}"
		;;
	h) Usage
	   exit 1;;
esac
done
shift $(($OPTIND - 1))

CksumProg="$CurDir/pkginstall/scripts/synocksum"
RealCksumProg="/usr/bin/cksum"
CksumFile="checksum.syno"

SynoDoCksum()
{
	if [ ! -d "$1" ]; then
		if [ -b "$1" ]; then
			# 0 0 b 117 2552
			Cksum3=$(($Cksum3+117))
			Cksum4=$(($Cksum4+2552))
			echo "0 0 $1 117 2552"	>> $CksumFile
		elif [ -c "$1" ]; then
			# 0 0 c 130 1814
			Cksum3=$(($Cksum3+130))
			Cksum4=$(($Cksum4+1814))
			echo "0 0 $1 130 1814"	>> $CksumFile
		elif [ -p "$1" ]; then
			# 0 0 p 51  1824
			Cksum3=$(($Cksum3+51))
			Cksum4=$(($Cksum4+1824))
			echo "0 0 $1 51 1824"	>> $CksumFile
		else
			if [ -L "$1" ]; then
				# 0 0 L Sz+Off Off
				IsSymbolic="1"
				echo -n "0 0 $1 "	>> $CksumFile
			else
				# regular file
				IsSymbolic="0"
				RealCksum=`${RealCksumProg} -o 3 $1`
				Field1=`echo $RealCksum | awk '{print $1}'`
				Field2=`echo $RealCksum | awk '{print $2}'`
				#Cksum1=$(($Cksum1+$Field1))
				Cksum2=$(($Cksum2+$Field2))
				echo -n "$Field1 $Field2 $1 "	>> $CksumFile
			fi
			CksumLine=`$CksumProg -c $1`
			Field3=`echo $CksumLine | awk '{print $1}'`
			Field4=`echo $CksumLine | awk '{print $2}'`
			Cksum3=$(($Cksum3+$Field3))
			Cksum4=$(($Cksum4+$Field4))
			echo "$Field3 $Field4"	>> $CksumFile
		fi
	fi
}
Cksum="Y"

SSTar()
{
	if [ -n "$1" ]; then
		if [ "Y" = "$Cksum" ]; then
			#Cksum1=0
			Cksum2=0
			Cksum3=0
			Cksum4=0
			TmpCurDir=`pwd`
			rm -f $CksumFile
			for ThisFile in $@;
			do
				if [ -d "$ThisFile" ]; then
					FileList=`find $ThisFile -name "*" -print`
					for Subfile in $FileList;
					do
						SynoDoCksum $Subfile
					done
				else
					SynoDoCksum $ThisFile
				fi
			done
			if [ "${ADD_SELF_CKSUM}" = "Y" ]; then
				echo "#Synocksum $Cksum2 $Cksum3 $Cksum4" >> $CksumFile
			fi
			cd $TmpCurDir
			if [ "${DO_TAR}" = "Y" ]; then
				tar cpf ${PATCH_NAME} $@ $CksumFile
				rm -f $CksumFile
			fi
		else
			tar cpf ${PATCH_NAME} $@
		fi
	else
		Usage
		exit 1
	fi
}

echo "SSTar ${PATCH_NAME}"
echo "Component: $1"
SSTar $1

