#!/bin/sh
#
# This script does an umount call for each folder that needs to be
# unmounted, and an mount call whenever a new virtualhost is active.
# It does that by comparing /proc/mounts and /var/lib/dtc/etc/aufs_list
# which is generated by DTC.
#
# If for some reason you need to umount everything, you can do:
# for i in `cat /proc/mounts | grep aufs | cut -d" " -f2 | more` ; do umount $i ; done
# which will umount all aufs mounts present in the system
#
# Note that since this script is checking against all mounted AUFS,
# you cannot use AUFS for anything else than DTC.
# An ignore list should be implemented to avoid such an issue, but
# for the moment, I have no time to implement it.

set -e

if [ "${1}" = -q ] ; then
	VERBOSE=0
else
	VERBOSE=1
fi

echoIfVerbose () {
	if [ "${VERBOSE}" = "1" ] ; then
		echo $1
	fi
}

echoIfVerbose "Computing lists of mounts and unmounts..."
# List all line numbers of /proc/mounts holding an aufs filesystem
CNT=0
LINES=""
for i in `cat /proc/mounts | cut -d" " -f3` ; do
	CNT=$(( ${CNT} + 1 ))
	if [ "${i}" = "aufs" ] ; then
		LINES=${LINES}"${CNT} "
	fi
done

# Compute list of already mounted subdomains.aufs/XXX
MOUNTED_LIST_FILE=`mktemp -t DTC_MOUNTED_LIST_FILE.XXXXXX`
for line_num in ${LINES} ; do
	LINE=`cat /proc/mounts | head -n ${line_num} | tail -n 1`
	TARGET=`echo ${LINE} | cut -d" " -f2`
	echo ${TARGET} >>${MOUNTED_LIST_FILE}
done

# Sort the result list of already mounted subdomains.aufs/XXX
SORTED_MOUNTED_LIST_FILE=`mktemp -t DTC_MOUNTED_LIST_FILE.XXXXXX`
cat ${MOUNTED_LIST_FILE} | sort >${SORTED_MOUNTED_LIST_FILE}
rm ${MOUNTED_LIST_FILE}

# Compute list of subdomains.aufs/XXX that we would like to see mounted
TOMOUNT_LIST_FILE=`mktemp -t DTC_TOMOUNT_LIST_FILE.XXXXXX`
CNT=0
for i in `cat /var/lib/dtc/etc/aufs_list` ; do
	SUBDOMAIN=`basename ${i}`
	TMP=`dirname ${i}`
	TARGET=`dirname ${TMP}`/subdomains.aufs/${SUBDOMAIN}
	echo ${TARGET} >>${TOMOUNT_LIST_FILE}
done

# Sort the result of subdomains.aufs/XXX that we would like to see mounted
SORTED_TOMOUNT_LIST_FILE=`mktemp -t DTC_SORTED_TOMOUNT_LIST_FILE.XXXXXX`
cat ${TOMOUNT_LIST_FILE} | sort >${SORTED_TOMOUNT_LIST_FILE}
rm ${TOMOUNT_LIST_FILE}

# Compute differences beetween lists
UMOUNT_LIST=`comm -23 ${SORTED_MOUNTED_LIST_FILE} ${SORTED_TOMOUNT_LIST_FILE}`
MOUNT_LIST=`comm -13 ${SORTED_MOUNTED_LIST_FILE} ${SORTED_TOMOUNT_LIST_FILE}`

# Umount what's needed
echoIfVerbose "umount list:"
for i in ${UMOUNT_LIST} ; do
	echoIfVerbose umount ${i}
	umount ${i} || true
done

# Mount what's not mounted yet
echoIfVerbose "mount list:"
for i in ${MOUNT_LIST} ; do
	SUBDOMAIN=`basename ${i}`
	TMP=`dirname ${i}`
	TARGET=`dirname ${TMP}`/subdomains.aufs/${SUBDOMAIN}
	SOURCE=`dirname ${TMP}`/subdomains/${SUBDOMAIN}
	echoIfVerbose "mount -t aufs -o br:${SOURCE}=rw:/var/lib/dtc/sbox_copy=ro none ${TARGET}"
	mount -t aufs -o br:${SOURCE}=rw:/var/lib/dtc/sbox_copy=ro none ${TARGET} || true
done
