#!/usr/bin/perl
#
# Copyright (c) 2003 Stefan Moeding <s.moeding@setuid.de>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#       $Id$
#

#
# Ausführung eines Programmes innerhalb eines kritischen Abschnittes.
# Der kritische Abschnitt wird durch eine Semaphore geschützt, die
# durch ein Lockfile implementiert wird.  Unter Nutzung des gleichen
# Lockfiles für mehrere Programme kann gewährleistet werden, daß zu
# einem Zeitpunkt nur eines der Programme läuft.  Durch eine Option
# kann gesteuert werden, ob auf die Freigabe der Semaphore gewartet
# oder dieses Script ohne den eigentlichen Programmaufruf beendet
# werden soll.
#
# Die für die Semaphore genutzte Datei wird durch dieses Script nicht
# gelöscht.  Die Datei alleine sagt auch nichts über den Zustand des
# Locks aus, da das Lock durch ein Lock des Betriebssystemes auf der
# Datei realisiert ist.  Damit wird das Lock bei einem unerwarteten
# Programmabsturz automatisch freigegeben.
#

use strict;


##############################################################################
#
# Auswertung der Optionen
#
# Erlaubt sind die Optionen '--wait' oder '--nowait' sowie die
# mandatorische Option --lock, mit der die für das Locking benutzte
# Datei angegeben wird.
#
my $done  = 0;
my $delay = 1;
my $wait  = 0;
my $lock  = undef;

while (($#ARGV >= 0) && (substr($ARGV[0], 0, 2) eq "--")) {
  my $opt = shift;

  if ($opt eq "--wait") {
    $wait = 1;
    next;
  }

  if ($opt eq "--nowait") {
    $wait = 0;
    next;
  }

  if (substr($opt, 0, 7) eq "--lock=") {
    $lock = substr($opt, 7);
    next;
  }

  if ($opt eq "--lock") {
    &usage if ($#ARGV < 1);
    $lock = shift;
    last;
  }

  # Option wurde nicht erkannt, also Fehler
  &usage;
}

&usage if (($#ARGV < 0) || !defined($lock) || ($lock eq ""));


##############################################################################
#
# Lock holen
#
# - Bei der Option --wait wird solange gewartet, bis das Lock
#   erfolgreich belegt werden konnte.
# - Ohne die Option --wait oder bei der Option --nowait gibt es nur
#   einen Versuch zur Belegung des Locks.  Ist dieser erfolglos, wird
#   das Programm mit dem Exitcode 255 verlassen.
#
while(! $done) {
  open(LOCKFILE, ">$lock") || die "$0: $! ($lock)\n";

  if (flock(LOCKFILE, 6)) {
    $done = 1;
    last;
  }

  close(LOCKFILE);
  exit 255 if ($wait == 0);

  sleep $delay;
  $delay <<= 1 if ($delay < 60);
}


##############################################################################
#
# Angegebenes Programm aufrufen
#
if (system @ARGV) {
  warn "$0: $! ($ARGV[0])\n";
}


##############################################################################
#
# Lock wieder freigeben
#
close(LOCKFILE);

exit 0;


sub usage {
  die "Usage: $0 [--wait] --lock=<lockfile> <program> [<args> ...]\n"
}
