#!/bin/sh

# Mount filesystems from the host into the guest chroot environment
daemon_host_mount_start () {
    # Mount /TMP
    if [ ${MOUNT_HOST_TMP} == 1 ]; then
        daemon_log_debug "Mounting host /tmp onto $MEDIACASTER_DIR/TMP"
        daemon_host_mount_mount /tmp "$MEDIACASTER_DIR/TMP"
    fi

    # Mount /mnt
    if [ ${MOUNT_HOST_MNT} == 1 ]; then
        daemon_log_debug "Mounting host /mnt onto $MEDIACASTER_DIR/mnt"
        daemon_host_mount_mount /mnt "$MEDIACASTER_DIR/mnt"
    fi

    # Mount /dev
    if ! grep -q "^[^ ]* $MEDIACASTER_DIR/dev " /proc/mounts; then
        daemon_log_debug "Mounting host /dev onto $MEDIACASTER_DIR/dev"
        daemon_host_mount_mount -o bind /dev "$MEDIACASTER_DIR/dev"
    fi

    # Mount /proc
    if ! grep -q "^[^ ]* $MEDIACASTER_DIR/proc " /proc/mounts; then
        daemon_log_debug "Mounting host /proc onto $MEDIACASTER_DIR/proc"
        daemon_host_mount_mount -o bind /proc "$MEDIACASTER_DIR/proc"
    fi

    # Mount /sys
    if ! grep -q "^[^ ]* $MEDIACASTER_DIR/sys " /proc/mounts; then
        daemon_log_debug "Mounting host /sys onto $MEDIACASTER_DIR/sys"
        daemon_host_mount_mount -o bind /sys "$MEDIACASTER_DIR/sys"
    fi
}

# Unmount host filesystems that were mounted at the start
daemon_host_mount_stop () {
	if grep -q "^[^ ]* $MEDIACASTER_DIR/sys " /proc/mounts; then
        daemon_log_debug "Unmounting $MEDIACASTER_DIR/sys"
        daemon_host_mount_umount "$MEDIACASTER_DIR/sys"
	fi

	if grep -q "^[^ ]* $MEDIACASTER_DIR/proc " /proc/mounts; then
        daemon_log_debug "Unmounting $MEDIACASTER_DIR/proc"
        daemon_host_mount_umount "$MEDIACASTER_DIR/proc"
	fi

	if grep -q "^[^ ]* $MEDIACASTER_DIR/dev " /proc/mounts; then
        daemon_log_debug "Unmounting $MEDIACASTER_DIR/dev"
        daemon_host_mount_umount "$MEDIACASTER_DIR/dev"
	fi

	if grep -q "^[^ ]* $MEDIACASTER_DIR/mnt " /proc/mounts; then
        daemon_log_debug "Unmounting $MEDIACASTER_DIR/mnt"
        daemon_host_mount_umount "$MEDIACASTER_DIR/mnt"
	fi

	if ${BUSYBOX_GUEST} grep -q "^[^ ]* $MEDIACASTER_DIR/TMP " /proc/mounts; then
        daemon_log_debug "Unmounting $MEDIACASTER_DIR/TMP"
		daemon_host_mount_umount "$MEDIACASTER_DIR/TMP"
	fi
}

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

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