#!/bin/ash
# remove whiteouts from pup_save/pup_rw
# use with care!
# jamesbond 2015
#

### configuration
APPTITLE="Whiteout Cleaner"
DIRS_TO_CLEAN="/aufs/pup_rw /aufs/pup_save /aufs/pup_multi"

#### helpers
# $1 - prompt, return true/false
yesno() {
	printf "%s" "$1"
	read input
	case $input in
		[Yy][Ee][Ss]) return 0 ;;
	esac
	return 1;
}

# $1-action
clean_whiteout() {
	for dir in $DIRS_TO_CLEAN; do
		echo Cleaning $dir ...
		find $dir -depth -name ".wh..wh.*" -prune -o -name ".wh.*" -print $ACTION 2>/dev/null
		echo "----"
	done
}

aufs_reval() {
	printf "Refreshing aufs cache..."
	busybox mount -i -t aufs -o remount,udba=reval aufs /
	echo "done."
}

### main
if ! test -t 0; then
	Xdialog --title "Error!" --infobox "Must run from terminal!" 0 0 10000
	exit 1
fi

if [ $(id -u) -ne 0 ]; then
	echo Must run as root.
	exit
fi

# caution
if ! [ "$1" = "yes" ]; then
	echo Running in dry-run/trial mode, nothing is actually changed.
	ACTION=""
else
	yesno "Warning: removing whiteout can have unintended consequences.
Click YES or type 'yes' to continue: " || exit
	ACTION="-delete"
fi
#echo $ACTION

# do it
echo "----"
clean_whiteout "$ACTION"
[ "$ACTION" ] || echo "Dry-run only, nothing above is actually deleted.
Pass 'yes' as parameter to really make the changes."
[ "$ACTION" ] && echo "All the above whiteouts are now gone." && aufs_reval

