#!/bin/sh

set -e

_append() {
	local g="${1}"
	local n="${2}"
	local i

	i=1
	while [ ${i} -le ${n} ]; do
		sed -i -e '$ s/^\(.*\)$/\1'${i}'/' "${g}"
		sed -i -e '$ s/^\(.*\)$/\1'${i}'/' "${g}"
		sed -i -e '$ s/^\(.*\)$/\1\n'${i}'x\1/' "${g}"
		i=$((${i}+1))
	done
	:
}

f="$(basename "$(mktemp --tmpdir="$(pwd)" "f-XXX")")"
echo "filename ${f}"
u="u-${f#*-}"
l="l-${f#*-}"
r="r-${f#*-}"

c="${1:-"10"}"
[ ${c} -ge 10 ] || c=10

echo "0" > "${f}"
mkdir "${u}"
mkdir "${l}"
mkdir "${r}"

_append "${f}" "10"
cp "${f}" "${l}/${f}"

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

_append "${f}" "${c}"
_append "${r}/${f}" "${c}"

diff "${f}" "${r}/${f}"

umount ${r}

echo "done."
:
