#!/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
    
    if [ $lock_count -eq 0 ]; then
        echo "Remounting root partition read-write"
        mount -o remount,rw / || {
            echo "Unable to remount root partition" >&2
            exit 1
        }
    else
        echo "Root partition already read-write by $lock_count other callers"
    fi
    expr $lock_count + 1 > "$TEMPFILE"
) 3> /run/lock/3d-p/coreutils-rw
exit 0
