#!/n/gnu/bin/perl -w

use IPC::SysV qw(IPC_CREAT);

$BASEDIR="/home/staff/meidanis/aulas/mc600/PROLOG";
$SUBMDIR="$BASEDIR/submdir";
$CAMPDIR="$BASEDIR/campdir";
$PUBDIR="/home/staff/meidanis/public_html/courses/mc600/200002/PrologCamp";

$IPC_KEY = 1235;
#$IPC_PERM= 0666;
$key = semget($IPC_KEY, 1, 0666 | IPC_CREAT );
print "semaphore $key\n";

$count=$ARGV[0];

while (1) {
    # get the semaphore key
    
    $key = semget($IPC_KEY,  0 , 0 );
    die if !defined($key);
    print "got key $key\n";
    
    $semnum = 0;
    $semflag = 0;
    
    # 'take' semaphore
    # wait for semaphore to be zero
    $semop = 0;
    $opstring1 = pack("sss", $semnum, $semop, $semflag);
    
    # Increment the semaphore count
    $semop = 1;
    $opstring2 = pack("sss", $semnum, $semop,  $semflag);
    $opstring = $opstring1 . $opstring2;
    
    semop($key,$opstring) || die "$!";
    print "got semaphore; copying players\n";
    
    # copia tudo & exec. campeonato
    print "count is $count\n";
    system("/bin/rm -f $CAMPDIR/*");
    system("cp -p $SUBMDIR/* $CAMPDIR");
    
    # 'give' the semaphore
    # run this in the original process and you will see
    # that the second process continues
    
    $key = semget($IPC_KEY, 0, 0);
    die if !defined($key);
    
    $semnum = 0;
    $semflag = 0;
    
    # Decrement the semaphore count
    $semop = -1;
    $opstring = pack("sss", $semnum, $semop, $semflag);
    
    semop($key,$opstring) || die "$!";
    print "released semaphore; going to tour and then sleep\n";

    system("$PUBDIR/execP.bash $count");
    $count = 0 if (++$count == 10);
    print "tournament done\n";
    
    sleep(60);			# 60 seconds
    print "Awake!\n";
}

    
    
    
