# -*- sh -*-
# vim:ft=sh:ts=8:sw=4:noet

LOCKFILE="/var/run/hibernate-script.pid"
LOCKFILE_IN_USE=

AddSuspendHook 01 LockFileGet
AddResumeHook 01 LockFilePut

# LockFileGet: test if a lockfile already exists, and create one if not. If it
# does exist, returns 1 to indicate the script should abort unless using
# --force. This code has race conditions. We could probably do something
# fancier with symlinks if we cared, but the worst that would happen if the
# race condition was hit, is we suspend twice. Big whoop.
LockFileGet() {
    local other_pid
    if [ -f "$LOCKFILE" ] ; then
	read other_pid < $LOCKFILE
	case $other_pid in *[!0-9]*) other_pid= ;; esac
	if [ -n "$other_pid" ] && kill -0 $other_pid ; then
	    vecho 0 "$EXE: Another hibernate process is already running ($other_pid)."
	    vecho 0 "$EXE: If this is stale, please remove $LOCKFILE."
	    return 1 # abort unless forced
	fi
	rm -f $LOCKFILE
    fi
    echo $$ > $LOCKFILE
    LOCKFILE_IN_USE=1
    return 0
}

# Remove the lockfile if we created one. Again, not foolproof as this may not
# have been our lock file.
LockFilePut() {
    [ -n "$LOCKFILE_IN_USE" ] && rm -f $LOCKFILE
    return 0
}

