#!/usr/bin/perl
use strict;
use File::Path qw/make_path/;

my $pidpath = '/tmp/runonce_pid';

if(!-d $pidpath) {
        make_path($pidpath) || die "Unable to create $pidpath: $!\n";
        chmod(0777, $pidpath) || die "Unable to chmod $pidpath: $!\n";
}

my $waitmode=0;
if(lc($ARGV[0]) eq '-w') {
        $waitmode=1;
        shift(@ARGV);
}

my($tag,@cmd)=@ARGV;
if(!$tag || !@cmd) {
        die "Usage: $0 <tag> <cmd>\n";
}

my $file = "$pidpath/$tag";
for(;;) {
        if(-e $file) {
                open(IN, $file) || die "Unable to read $file: $!\n";
                my $pid=<IN>;
                close(IN);
                chomp($pid);

                if(kill(0, $pid)) {
                        print "$pid is alive\n";
                        exit(0) unless($waitmode);
                        sleep(1);
                } else {
                        last;
                }
        } else {
                last;
        }
}

open(OUT, ">", $file) || die "Unable to write $file: $!\n";
print OUT $$;
close(OUT);

my $res=system(@cmd);

unlink($file) || die "Unable to unlink $file: $!\n";
exit($res);