#!/bin/bash
#
# Script to "commit" aufs tmpfs changes back to the underlying persistent filesystem.
#

SCRIPT="`realpath $0`"
ROOT=/.rw
AUFS=$ROOT/.tmpfs
arg1="$1"

MIRRORDIR=/usr/bin/mirrordir
if [ ! -x $MIRRORDIR ]; then
	echo "$MIRRORDIR: not found; aborting." >&2
	exit 1
fi

COMMIT=""
if [ "$1" = "--commit" ]; then
	COMMIT="$1"
	shift
fi

function doit(){
	echo "$*"
	[ "$COMMIT" = "--commit" ] && $*
}

if [ "$1" = "" ]; then
	cd $AUFS || exit 1
	find . -type f -name .wh.\* | xargs -n1 $SCRIPT $COMMIT WHITEOUT
	doit sync

	cd $AUFS || exit 1
	find . | xargs -n1 $SCRIPT $COMMIT COPY
	doit sync

	[ "$COMMIT" = "--commit" ] || (echo ;echo "$SCRIPT: Dry run complete. Use --commit to do it for real"; echo)
	exit 0
fi

if [ "$1" = "WHITEOUT" ]; then
	cd $AUFS || exit 1
	dir="${2%%/.wh.*}"
	fn="${2##*/.wh.}"
	if [ "$dir" = "." ]; then
		[ "$fn" = ".rw" -o "$fn" = ".aufs" -o "$fn" = ".tmpfs" ] && exit 0
	fi
	if [ "$fn" = ".wh..opq" ]; then
		if [ -d "$ROOT/$dir" ]; then
			if [ -d "$dir" ]; then
				doit $MIRRORDIR -v --exclude-regexp '.*/[.]wh[.].*' "$dir" "$ROOT/$dir"
			else
				doit rm -rf "$ROOT/$dir"
			fi
		fi
		exit 0
	fi
	if [ "$dir/.wh.$fn" = "$2" ]; then
		[ -e "$ROOT/$dir/$fn" ] && doit rm -rf "$ROOT/$dir/$fn"
	fi
	exit 0
fi

if [ "$1" = "COPY" ]; then
	cd $AUFS || exit 1
	if [ -d "$2" ]; then
		[ "$2" = "./.wh..wh.plink" ] && exit 0
		cd $AUFS || exit 1
		dir="${2%%/.wh.*}"
		if [ ! -e "$ROOT/$dir" ]; then
			doit mkdir -p "$ROOT/$dir"
			doit $MIRRORDIR -v --exclude-regexp '.*/[.]wh[.].*' "$dir" "$ROOT/$dir"
		fi
		exit 0
	fi
	[ "${2:0:6}"  = "./.wh."     ] && exit 0
	[ "${2:0:6}"  = "./tmp/"     ] && exit 0
	[ "${2:0:10}" = "./var/tmp/" ] && exit 0
	dir="${2%%/*}"
	fn="${2##*/}"
	[ "${fn:0:4}" = ".wh." ] && exit 0
	[ ! -e "$ROOT/$dir" ] && doit mkdir -p "$ROOT/$dir"
	if [ -f "$2" -a -f "$ROOT/$2" ]; then
		if diff -q "$2" "$ROOT/$2" >/dev/null ; then
			[ "$2" -nt "$ROOT/$2" ] && touch -m -r "$2" "$ROOT/$2"
			exit 0
		fi
	fi
	doit cp -dp "$2" "$ROOT/$2"
	exit 0
fi

echo "$SCRIPT: huh?  $*" >&2
