#!/bin/sh

[ $(id -u) -ne 0 ] && {
    echo "Super-user privileges are required to remount /"
    exit 1
}

TEMPFILE="/run/shm/3d-p/coreutils-rw"
( flock 3 || exit 1
    if [ -f "$TEMPFILE" ]; then
        lock_count=$(cat "$TEMPFILE")
    else
        lock_count=0
    fi
    lock_count=$(expr $lock_count - 1)
    
    if [ $lock_count -le 0 ]; then
        #Clean up first, in case remounting fails and the caller ignores it
        #An attentive caller is expected to report the issue to the operator
        #so that it can be dealt with properly, rather than attempt another call;
        #a race-condition is sub-optimal, and it's possible that a later caller
        #might resolve the situation, so it should not be blocked
        [ -f "$TEMPFILE" ] && rm "$TEMPFILE"
        
        echo "Remounting root partition read-only"
        mount -o remount,ro / || {
            echo "Unable to remount root partition" >&2
            exit 1
        }
    else
        echo "Root partition still in use by $lock_count callers; not remounting"
        echo $lock_count > "$TEMPFILE"
    fi
) 3> /run/lock/3d-p/coreutils-rw
exit 0
