#!/bin/sh

if [ ! -f /etc/default/mount_checks ]; then
    echo "/etc/default/mount_checks required but not found; exiting"
    exit 1
fi

. /etc/default/mount_checks

usage() {
    echo "Usage: rootfs_open [-w|-r|-h]"
    echo "Make rootfs writable or readable."
    echo " -w          make writable (default)"
    echo " -r          make read-only and reboot"
#    echo " -p          persistent across reboots"
    echo " -t          make read-write until the next reboot, then revert to original mode"
    echo " -h|--help   show this usage screen"
}

PERSIST=1
WRITABLE=1
PROG=$(basename $0)

for i
do
case "$i" in
#    -p) shift; PERSIST=1;;
    -w) shift; WRITABLE=1;;
    -r) shift; WRITABLE=0;;
    -t) shift; PERSIST=0;;
    *) usage; exit 1;;
esac
done

# Tell mountall.sh to run fsck on next boot.  If /'s been rw it needs
# to be checked for damage ASAP.  It's easier and safer to always set
# it than integrate with existing logic.
test -e /var/.rootfs_fsck || touch /var/.rootfs_fsck

if [ "${WRITABLE}" -eq "1" ]; then
    mount -o remount,rw /
    mount -o remount,rw /boot
    if [ "${PERSIST}" -eq "1" ]; then
        echo "1" > ${REMOUNT_TOKEN}
    fi
else  # WRITABLE not set (to 1)
    if [ "${PERSIST}" -eq "1" ]; then
        mount -o remount,rw /
        echo "0" > ${REMOUNT_TOKEN}
        sync
    fi
    echo "rebooting..."
    reboot
fi

exit 0
