#!/bin/sh
# Enter full debian system mode.
# This program should be fully idempotent.

set -e

CONFDIR=/etc/flashybrid
. $CONFDIR/config

# Trim trailing slash from FLASHMOUNT; this is necessary so I can use
# $FLASHMOUNT$dir below when building up mount points, and not get extra
# slashes.
FLASHMOUNT=${FLASHMOUNT%%/}

is_mounted () {
	grep -q " $1 " /proc/mounts
}

if [ -n "$DISKMOUNT" ]; then
	if ! is_mounted $DISKMOUNT; then
		mount $DISKMOUNT
	fi
		
	if [ -e $CONFDIR/partial ]; then
		for file in $(grep -v '^#' $CONFDIR/partial); do
			dir=${file%/*} # dirname
			if [ -e $FLASHMOUNT$dir/.partial ] || \
			   [ ! -e $FLASHMOUNT$file ]; then
				if is_mounted $FLASHMOUNT$dir; then
					umount $FLASHMOUNT$dir
				fi
				mount --bind $DISKMOUNT$dir $FLASHMOUNT$dir
			fi
		done
	fi

	if [ -e $CONFDIR/diskstore ]; then
		for dir in $(grep -v '^#' $CONFDIR/diskstore); do
			if [ ! -e $DISKMOUNT$dir ]; then
				echo "Skipping $dir, not in $DISKMOUNT" >&2
			elif [ ! -e $FLASHMOUNT$dir ]; then
				echo "Skipping $dir, no mount point at $FLASHMOUNT$dir" >&2
			else
				if is_mounted $FLASHMOUNT$dir; then
					umount $FLASHMOUNT$dir
				fi
				mount --bind $DISKMOUNT$dir $FLASHMOUNT$dir
			fi
		done
	fi
fi

eval $FULL_CMDS || true
