#!/bin/sh

PORT=""
OPTS=""

while [ $# != 0 ] ;do
	case $1 in
		-*)
			# unused for now
			OPTS="${OPTS} $1"
			;;
		*)
			PORT="${PORT} $1"
			;;
	esac
	shift
done

if [ "${PORT}" != "" ] ;then
	for p in $PORT ;do
		WD="`port work ${p}`"
		STATEFILE=${WD}/.macports.${p}.state
		PFILE="`port dir ${p}`/Portfile"
		CHKSUM="`openssl sha256 -r ${PFILE} | sed -e 's| \*.*||g'`"
		if [ -e ${STATEFILE} ] ;then
			OCHKSUM="`fgrep 'checksum:' ${STATEFILE} | sed -e 's|checksum: ||g'`"
			if [ "${OCHKSUM}" != "${CHKSUM}" ] ;then
				echo "Changing ${p}'s checksum from ${OCHKSUM} to ${CHKSUM}"
				cp -p ${STATEFILE} ${STATEFILE}.bak
				sed -e "s|checksum: .*|checksum: ${CHKSUM}|g" < ${STATEFILE}.bak > ${STATEFILE}
				rm -f ${STATEFILE}.bak
			fi
		fi
	done
else
	echo "Usage: `basename $0` <port1> [port2 [port3 [...]]]"
	echo "This utility updates the checksum in the port's state file"
fi
