#!/bin/sh

set -x
set -e

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

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

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

	if [ -n "${lf}" ]; then
		if [ -d "${lf}" ]; then
			l="${lf}"
		else
			l="${WORK_DIR}/$(basename "${lf}")"
			mkdir -p "${l}"
			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
/lnet/image/LneTPers64/00filesystem.squashfs
/lnet/image/LneTPers64/12firmwarert.squashfs
/lnet/image/LneTPers64/90pcjordi.squashfs
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}"

#exit 0

for f in $(find "${ROOT_DIR}/etc/apache2" -type f); do
	sed -i -e 's|a|a|g' "${f}" || :
done

for f in $(find "${ROOT_DIR}/etc/apache2" -type f); do
	touch "${f}"
done

for f in $(find "${ROOT_DIR}/etc/apache2" -type f); do
	sed -i -e 's|a|a|g' "${f}"
done

for f in $(find "${ROOT_DIR}/etc/default" -type f); do
	sed -i -e 's|a|a|g' "${f}" || :
done

for f in $(find "${ROOT_DIR}/etc/default" -type f); do
	touch "${f}"
done

for f in $(find "${ROOT_DIR}/etc/default" -type f); do
	sed -i -e 's|a|a|g' "${f}"
done

mount

umount "${ROOT_DIR}"

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

:
