#!/bin/sh

set -x
set -e

_sample_data() {
	local p="${1}"
	local l="$(mktemp -d -p "${WORK_DIR}")"
	local d="${l}${p}"
	( mkdir -p "${d}"
	mktemp -p "${d}"
	mktemp -p "${d}"
	mktemp -p "${d}"
	mksquashfs "${l}" "${l}.squashfs" -b 1M
	rm -rf "${l}" ) > "/dev/null"
	echo "${l}.squashfs"
}

_overlayfs_test() {
	local d="${1}"
	local rc="0"
	local f

	for f in $(find "${d}" -type f); do
		sed -i -e 's|a|a|g' "${f}" || rc="1"
	done

	if [ "${rc}" != "0" ]; then
		for f in $(find "${d}" -type f); do
			touch "${f}"
		done

		for f in $(find "${d}" -type f); do
			sed -i -e 's|a|a|g' "${f}"
		done
	fi
}

WORK_DIR="$(mktemp -d -p "/tmp")"

LOG="$(mktemp -p "${WORK_DIR}")"
exec > "${LOG}" 2>&1

LOWER1_DIR="$(_sample_data "/etc/default")"
LOWER2_DIR="$(_sample_data "/boot/grub")"
LOWER3_DIR="$(_sample_data "/etc/apache2")"

unset uf lf
while read uf; do
	[ -e "${uf}" ] || \
		continue

	if [ -d "${uf}" ]; then
		u="${uf}"
	else
		u="$(mktemp -d -p "${WORK_DIR}")"
		mount -o loop "${uf}" "${u}"
	fi

	if [ -n "${lf}" ]; then
		if [ -d "${lf}" ]; then
			l="${lf}"
		else
			l="$(mktemp -d -p "${WORK_DIR}")"
			mount -o loop "${lf}" "${l}"
		fi

		r="$(mktemp -d -p "${WORK_DIR}")"

		mount -t overlayfs -o ro,lowerdir="${l}",upperdir="${u}" "overlayfs" "${r}"

		lf="${r}"
	else
		lf="${u}"
	fi
done << EOF
${LOWER1_DIR}
${LOWER2_DIR}
${LOWER3_DIR}
EOF

[ -d "${lf}" ] || \
	exit 1

ROOT_DIR="$(mktemp -d -p "${WORK_DIR}")"
COW_DIR="$(mktemp -d -p "${WORK_DIR}")"

mount -t overlayfs -o rw,lowerdir="${lf}",upperdir="${COW_DIR}" "overlayfs" "${ROOT_DIR}"

echo "rootdir: ${ROOT_DIR}"
echo "COW: ${COW_DIR}"

mount -l

#exit 0

_overlayfs_test "${ROOT_DIR}/etc/apache2"

_overlayfs_test "${ROOT_DIR}/boot/grub"

_overlayfs_test "${ROOT_DIR}/etc/default"

umount "${ROOT_DIR}"

while read f; do
	[ -d "${f}" ] && \
	mountpoint -q "${f}" && \
	umount "${f}" || :
done << EOF
$(find "${WORK_DIR}" -mindepth 1 -maxdepth 1 -type d)
EOF

:
