#!/usr/bin/perl
# Copyright (C) 2002 William R Thomas <corvar@theonering.net>
# Last Changed by: $Author: corvar $
# on: $Date: 2002/12/27 10:50:52 $
# Version: $Revision: 1.0 $

# Maintainer: William R Thomas <corvar@theonering.net>
# Keywords: convenience

# This file is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License
# as published by the Free Software Foundation.

# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#

# Revision History:
# 1.0 Initial version;  Drop in replacement for calling 'ratpoison -c' 
#     directly.  Implements some rudimentary file locking which should
#     prevent a race condition resulting from two instances of
#     ratpoison -c being run in too short of a period of time.

# Requirements:
# Perl

# ratp-com.pl version: $Revision: 1.0 $


$lockfile = '/tmp/.ratp-com.'.$ENV{USER}.'lock';

if( -f $lockfile ) {
    $mtime = (stat($lockfile))[9];
    if($mtime < (time() - 60)) {
	unlink($lockfile);
	open(LOCK,">".$lockfile);
	print LOCK "$$";
	close(LOCK);
    } else {
	print STDERR "don't do it old file";
	exit;
    }
} else {
    open(LOCK,">".$lockfile);
    print LOCK "$$";
    close(LOCK);
}

if( -f $lockfile ) {
    open(LOCK,$lockfile);
    if(<LOCK> =~ /$$/) {
	system("/usr/bin/ratpoison","-c", @ARGV);
    } else {
	print STDERR "don't do it, bad lock";
	exit; 
    }
    close(LOCK);
} else {
    print STDERR "don't do it, lock disappeared";
}


unlink($lockfile);
