#!/bin/sh

readonly GIT=${GIT:-git}

echo "===> Removing work dirs..."

if [ "$(make -V PORTNAME)" ]; then
	depth=2
else
	[ "$(make -V PORTSTOP)" ] && depth=4 || depth=3
fi

wrk_dirs=$(find . -name "work*" -type d -depth $((depth-1)) | sed 's|^./||g')
if [ "$wrk_dirs" ]; then
	for wdir in $wrk_dirs; do
		if [ $depth -ne 2 ]; then
			dirname=$(dirname "$wdir")
			echo "===> Running 'make clean' in $dirname..."
			make_args="-C $dirname"
		else
			echo "===> Running 'make clean'..."
			make_args=""
		fi

		ret=$(make $make_args clean 2>/dev/null)
		if echo "$ret" | grep -q 'not writable'; then
			if [ $depth -ne 2 ]; then
				echo "  Failed to 'make clean' in $dirname"
			else
				echo "  Failed to 'make clean'"
			fi
		fi
	done
fi

if ! which "$GIT" >/dev/null; then
	echo "===> $GIT executable not found" >&2
	exit 1
fi
if $GIT show-branch >/dev/null 2>&1; then
	echo "===> Running '$GIT restore'..."
	$GIT restore .
	echo "===> Running '$GIT clean'..."
	$GIT clean --force -x

# TODO git status is sloooow
#	echo "===> Removing leftover files..."
#	$GIT status --short --ignored | while read line; do
#		status=$(echo "$line" | awk '{ print $1 }')
#		file=$(echo "$line" | awk ' { print $2 }')
#
#		[ ! "$status" -o ! "$file" ] && continue
#
#		if [ "$status" = '??' -o "$status" = '!!' ]; then
#			[ "$file" != "distfiles" ] || continue
#			echo "  $file"
#			rm -rf "$file"
#		else
#			echo "file=$file status=$status"
#		fi
#	done
fi
