#!/bin/sh

set -eu
set -x

UNION_TYPE="$1"

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)

ROOT_UNION_RO=
for i in $(seq 1 3); do
   mkdir "$SRCDIR/$i"
   install -o "$((100 + $i))" -g root -m 0700 -d "$SRCDIR/$i/dir"
   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//')

case "$UNION_TYPE" in
   overlayfs)
      sudo mount -t overlay \
           "-olowerdir=${ROOT_UNION_RO},upperdir=${ROOT_UPPERDIR},workdir=${ROOT_WORKDIR}" \
           overlay "$ROOT_MOUNTPOINT"
      ;;
   aufs)
      sudo mount -t aufs \
           -o "br=${ROOT_UPPERDIR}=rw:${ROOT_UNION_RO}=ro" \
           none "$ROOT_MOUNTPOINT"
      ;;
   *)
      echo "$UNION_TYPE not supported" >&2
      exit 1
      ;;
esac

sudo -u "#103" ls "${ROOT_MOUNTPOINT}/dir"
sudo -u "#102" ls "${ROOT_MOUNTPOINT}/dir"
sudo -u "#101" ls "${ROOT_MOUNTPOINT}/dir"
