#!/bin/sh /etc/rc.common
# Copyright (C) 2007 OpenWrt.org
# Copyright (C) 2010 Vertical Communications
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#


START=20

EXTRA_COMMANDS="overlay_enable whole_root_enable"
EXTRA_HELP="        overlay_enable    Reenable overlay rootfs. (After you fix it).
        whole_root_enable Reenable whole-disk rootfs.  (After you fix it)."

rootfs_enable() {
	local extroot_type="$1"
		
	if [ ! -d /tmp/${extroot_type}-disabled ]; then
		echo "No disabled ${extroot_type} present (/tmp/${extroot_type}-disabled).  Can't renable."
		exit 1
	fi
	
	rm -f /tmp/${extroot_type}-disabled/.extroot.md5sum
	rm -f /tmp/${extroot_type}-disabled/etc/extroot.md5sum
	echo "Please reboot router to complete re-enabling external rootfs."
}

overlay_enable() {
	rootfs_enable overlay
}

whole_root_enable() {
	rootfs_enable whole_root
}

do_mount() {
	local cfg="$1"
	config_mount_by_section "$cfg"
}

do_swapon() {
	local cfg="$1"
	config_swapon_by_section "$cfg"
}

do_unmount() {
	local cfg="$1"

	config_get target "$cfg" target
	config_get_bool enabled "$cfg" "enabled" '1'
	[ -n "$target" -a "$enabled" -gt 0 ] || return 0
	umount $target
}
	
do_swapoff() {
	local cfg="$1"

	config_get device "$cfg" device
	config_get_bool enabled "$cfg" "enabled" '1'
	[ -n "$device" -a  "$enabled" -gt 0 ] && type swapoff >/dev/null || return 0
	swapoff $device
}

start() {
	. /lib/functions/mount.sh

	config_load fstab
	mkdir -p /var/lock
	lock /var/lock/fstab.lck
	[ -e /tmp/fstab ] || {
		echo '# WARNING: this is an auto generated file, please use uci to set defined filesystems' > /tmp/fstab
	}
	lock -u /var/lock/fstab.lck
	config_foreach do_swapon swap
	config_foreach do_mount mount
	config_foreach do_swapon swap  # do swap a second time so that swap on filesystems is enabled
}

stop() {
	. /lib/functions/mount.sh

	config_load fstab
	config_foreach do_unmount mount
	config_foreach do_swapoff swap
	swapoff -a
}

restart() {
	stop
	sleep 1
	start
}
