#!/bin/sh

#GUEST_BIND_MOUNT_DIR=/tmp/mediaconnect_dir
#HOST_BIND_MOUNT_DIR="${MEDIACASTER_DIR}${GUEST_BIND_MOUNT_DIR}"
HOST_BIND_MOUNT_DIR="/tmp/mediaconnect_dir"

# Mount the standard set of bind mounts
daemon_bind_mount_start() {
	if [ ! -d ${HOST_BIND_MOUNT_DIR} ]; then
		daemon_log_info "Creating ${HOST_BIND_MOUNT_DIR}"
		mkdir -p ${HOST_BIND_MOUNT_DIR}
	fi

	daemon_bind_mount /etc
	daemon_bind_mount /home/0db
	daemon_bind_mount /var/lib/sqlite

	# General tmpfs directories, don't copy contents
	daemon_bind_mount /tmpHost 0
	daemon_bind_mount /tmp 0
	daemon_bind_mount /home/0external 0
}

# Unmount the standard set of bind mounts
daemon_bind_mount_stop() {
	daemon_bind_unmount /home/0external
	daemon_bind_unmount /tmp
	daemon_bind_unmount /tmpHost

	daemon_bind_unmount /var/lib/sqlite
	daemon_bind_unmount /home/0db
	daemon_bind_unmount /etc
}

# Overlay a writable copy of a directory via tmpfs
daemon_bind_mount () {
    # Set the location of the tmpfs mount for binding
    # NOTE: This means every bind mount must have a unique final path component
    local DEST="${HOST_BIND_MOUNT_DIR}/`basename $1`"
    local TARGET="${MEDIACASTER_DIR}$1"
    local COPY="$2"

    if [ "" == "$COPY" ]; then
    	COPY=1
    fi

    # Make sure the parent of the bind mount exists
    if [ ! -d ${HOST_BIND_MOUNT_DIR} ]; then
    	daemon_log_debug "Creating ${HOST_BIND_MOUNT_DIR}"
	    mkdir -p ${HOST_BIND_MOUNT_DIR}
	fi

    # Make sure we don't bind mount anything twice
	if grep -q "^[^ ]* ${TARGET} " /proc/mounts; then
	    daemon_log_debug "${TARGET} is already mounted"
		return
	fi

    # Make sure the tmpfs copy doesnt exist
	if [ -d "$DEST" ]; then
	    daemon_log_debug "Removing $DEST"
		rm -rf ${DEST}
	fi

    # Create the new tmpfs copy
    if [ "1" == "$COPY" ]; then
		daemon_log_debug "Copying ${MEDIACASTER_DIR}$1 to ${HOST_BIND_MOUNT_DIR}"
		cp -p -r ${TARGET} ${HOST_BIND_MOUNT_DIR}
	else
		mkdir -p ${DEST}
	fi

    # Mount the tmpfs copy onto the original directory
	daemon_log_debug "Mounting ${DEST} on ${TARGET}"
	daemon_bind_mount_mount -o bind ${DEST} ${TARGET}

	# Set the permissions just in case
	chmod 755 "${TARGET}"
}

daemon_bind_unmount () {
    local DEST="${HOST_BIND_MOUNT_DIR}/`basename $1`"
    local TARGET="${MEDIACASTER_DIR}$1"
	local SECONDS

	for SECONDS in 1 2 4 8 16
	do
		if grep -q "^[^ ]* ${TARGET} " /proc/mounts; then
			daemon_log_debug "Unmounting ${DEST} from ${TARGET}"
			daemon_bind_unmount_umount ${TARGET}
			if [ "$?" == "0" ]; then
				daemon_log_debug "Removing ${DEST}"
				rm -rf ${DEST}
				break
			else
				daemon_log_debug "Mount point still in use: ${TARGET}"
				daemon_log_debug "Sleeping ${SECONDS} seconds"
				sleep ${SECONDS}
			fi
		else
			break
		fi
	done
}

daemon_bind_mount_mount () {
	if [ "0" == "$isBuildroot" ]; then
		sudo mount $@
	else
		mount $@
	fi
}

daemon_bind_unmount_umount () {
	if [ "0" == "$isBuildroot" ]; then
		sudo umount $@ 2>/dev/null
	else
		umount $@ 2>/dev/null
	fi
}
