#!/bin/sh

PORT=""
PHASE=""

while [ $# != 0 ] ;do
	case $1 in
		-*)
			f=${1:1}
			case ${f} in
				fetch|checksum|extract|patch|patch-all|configure|build|destroot)
					PHASE="${PHASE} $f"
					;;
				*)
					echo "${f}: invalid install phase"
					exit 1
					;;
			esac
			;;
		*)
			PORT="${PORT} $1"
			;;
	esac
	shift
done

if [ "${PORT}" != "" -a "${PHASE}" != "" ] ;then
	for p in $PORT ;do
		WD="`port work ${p}`"
		STATEFILE=${WD}/.macports.${p}.state
		PFILE="`port dir ${p}`/Portfile"
		if [ -e ${STATEFILE} ] ;then
			# let's protect the user from the effects of forgetting port's -o option!
			port-update-state-checksum ${p}
			for f in ${PHASE} ;do
				case ${f} in
					patch-all)
						echo "Rewinding patch phase completely"
						cp -p ${STATEFILE} ${STATEFILE}.bak
						sed -e "/patch: .*/d" \
								-e "/target: org\.macports\.patch/d" < ${STATEFILE}.bak > ${STATEFILE}
						;;
					patch)
						echo "Rewinding patch phase up to the last patch applied successfully"
						cp -p ${STATEFILE} ${STATEFILE}.bak
						sed -e "/target: org\.macports\.${f}.*/d" < ${STATEFILE}.bak > ${STATEFILE}
						;;
					destroot)
						echo "Rewinding the destroot phase and removing the destroot directory"
						cp -p ${STATEFILE} ${STATEFILE}.bak
						sed -e "/target: org\.macports\.destroot/d" \
								-e "/target: org\.macports\.archivefetch/d" < ${STATEFILE}.bak > ${STATEFILE}
						rm -rf ${WD}/destroot*
						;;
					*)
						echo "Rewinding the ${f} phase"
						cp -p ${STATEFILE} ${STATEFILE}.bak
						sed -e "/target: org\.macports\.${f}.*/d" < ${STATEFILE}.bak > ${STATEFILE}
						;;
				esac
			done
			rm -f ${STATEFILE}.bak
		fi
	done
else
	echo "Usage: `basename $0` <-phase1> [<-phase2>] <port1> [port2 [port3 [...]]]"
	echo "This utility \"rewinds\" the specified phases in a port's build/install procedure, allowing them to be repeated"
	echo "Special cases:"
	echo "\t-destroot: also rewinds archivefetch, and causes the destroot directory to be removed,"
	echo "\t           so no \"file already exists\" conflicts can occur"
	echo "\t-patch: allows the patch phase to be repeated without resetting any information on"
	echo "\t        what patches were applied successfully"
	echo "\t-patch-all: allows the patch phase to be repeated completely, all patchfiles included"
fi
