#!/bin/sh

set -eu
set -x

SRCDIR=$(mktemp -d)
MEDIUM=$(mktemp -d)
MEDIUM_LOOPS_DIR=$(mktemp -d)

ROOT_OVERLAY_DIR=$(mktemp -d)
sudo mount -t tmpfs tmpfs "$ROOT_OVERLAY_DIR"
ROOT_UPPERDIR="$ROOT_OVERLAY_DIR/upperdir"
mkdir "$ROOT_UPPERDIR"
ROOT_WORKDIR="$ROOT_OVERLAY_DIR/workdir"
mkdir "$ROOT_WORKDIR"
ROOT_MOUNTPOINT=$(mktemp -d)

CHROOT_OVERLAY_DIR=$(mktemp -d)
sudo mount -t tmpfs tmpfs "$CHROOT_OVERLAY_DIR"
CHROOT_UPPERDIR="$CHROOT_OVERLAY_DIR/upperdir"
mkdir "$CHROOT_UPPERDIR"
CHROOT_WORKDIR="$CHROOT_OVERLAY_DIR/workdir"
mkdir "$CHROOT_WORKDIR"
CHROOT_MOUNTPOINT=$(mktemp -d)

# set up root filesystem
ROOT_UNION_RO=
for i in $(seq 1 3); do
   mkdir "$SRCDIR/$i"
   echo "$i" > "$SRCDIR/$i/bla"
   mksquashfs "$SRCDIR/$i" "$MEDIUM/$i.squashfs"
   mkdir "$MEDIUM_LOOPS_DIR/$i.squashfs"
   sudo mount -o loop "$MEDIUM/$i.squashfs" "$MEDIUM_LOOPS_DIR/$i.squashfs"
   ROOT_UNION_RO="$MEDIUM_LOOPS_DIR/$i.squashfs:${ROOT_UNION_RO}"
done
ROOT_UNION_RO=$(echo -n "$ROOT_UNION_RO" | perl -pE 's/:\z//')
sudo mount -t overlay \
     "-olowerdir=${ROOT_UNION_RO},upperdir=${ROOT_UPPERDIR},workdir=${ROOT_WORKDIR}" \
     overlay "$ROOT_MOUNTPOINT"

# set up chroot filesystem
CHROOT_UNION_RO=
ROOTFS_LOOPS_DIR="$ROOT_MOUNTPOINT/lib/live/mount/rootfs"
for i in $(seq 1 3); do
   mksquashfs "$SRCDIR/$i" "$MEDIUM/$i-chroot.squashfs"
   mkdir -p "$ROOTFS_LOOPS_DIR/$i-chroot.squashfs"
   sudo mount -o loop "$MEDIUM/$i-chroot.squashfs" "$ROOTFS_LOOPS_DIR/$i-chroot.squashfs" 
   CHROOT_UNION_RO="$ROOTFS_LOOPS_DIR/$i-chroot.squashfs:${CHROOT_UNION_RO}"
done
CHROOT_UNION_RO=$(echo -n "$CHROOT_UNION_RO" | perl -pE 's/:\z//')
sudo mount -t overlay \
     "-olowerdir=${CHROOT_UNION_RO},upperdir=${CHROOT_UPPERDIR},workdir=${CHROOT_WORKDIR}" \
     overlay "$CHROOT_MOUNTPOINT"
