#!/bin/sh
#(c) Copyright Barry Kauler, 13 February 2017. License: GPL V3 (/usr/share/doc/legal)
#passed in parameter is name of executable.
#'setup-container' has already run, at least once, to create the container.

[ ! $1 ] && exit 1
EXE="$1"

. /etc/DISTRO_SPECS
. /etc/rc.d/PUPSTATE #has BOOT_DEV, BOOT_FS, BOOT_DIR, WKG_DEV, WKG_FS, WKG_DIR, QSFS_PATH
mkdir -p /tmp/easy_containers
[ ! -d /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE} ] && exit 1

cd /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}
. ./configuration

#'sh0' is a pre-created container, see initramfs /skeleton, which has nothing in /dev
#note, same code in setup-container
if [ ! -e /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/.session/dev/pts ];then
 cp -f /usr/local/easy_containers/dev.tar.gz /tmp/easy_containers/
 cd /tmp/easy_containers
 tar -xf dev.tar.gz
 mkdir -p /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/.session/dev
 cp -a -f --remove-destination dev/* /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/.session/dev/
 sync
 rm -rf dev
 rm dev.tar.gz
 cd /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}
fi

#bottom ro layer
#note, path to q.sfs may change, if booting off usb stick.
mkdir -p .ro0
busybox mount -t squashfs -o loop,noatime ${QSFS_PATH}q.sfs .ro0
[ $? -ne 0 ] && exit 3

#170206 reintroducing aufs in the kernel:
if grep -qw aufs /proc/filesystems; then
 LAYERFS='aufs'
 RO='=ro'
else
 LAYERFS='overlay'
 RO=''
fi

#configuration file may specify extra sfs files to load...
EXTRASFS=''
for NUM in 4 3 2 1
do
 eval "ROsfs=\$EC_LAYER_RO${NUM}" #implements indirection. EC_LAYER_RO1='devx.sfs' in configuration file, will assign 'devx.sfs' to ROsfs
 if [ "$ROsfs" ];then
  ANAME="$(basename $ROsfs .sfs)"
  mkdir -p ./.${ANAME}
  mount -r -t squashfs -o noatime,loop /mnt/${WKG_DEV}/${WKG_DIR}repository/easy-${DISTRO_VERSION}/${ROsfs} .${ANAME}
  EXTRASFS=".${ANAME}${RO}:${EXTRASFS}"
 fi
done

if [ "$LAYERFS" == "aufs" ];then
 mount -t aufs -o br=.session=rw:${EXTRASFS}.ro0=ro aufs /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/container
else
 mount -t overlay -o lowerdir=${EXTRASFS}.ro0,upperdir=.session,workdir=.work overlay /mnt/${WKG_DEV}/${WKG_DIR}containers/${EXE}/container
fi
if [ $? -ne 0 ];then
 busybox umount .ro0
 #unmount any extra sfs files...
 for NUM in 4 3 2 1
 do
  eval "ROsfs=\$EC_LAYER_RO${NUM}" #implements indirection. EC_LAYER_RO1='devx.sfs' in configuration file, will assign 'devx.sfs' to ROsfs
  if [ "$ROsfs" ];then
   ANAME="$(basename $ROsfs .sfs)"
   busybox umount .${ANAME}
  fi
 done
 exit 4
fi

exit 0
###end###
