#!/usr/bin/env perl
use strict;
use warnings;
use diagnostics;

use lib "./lib";
use HotSaNICparser;

# read global settings
#
my %CONFIG=HotSaNICparser::get_config("./");

my $PIDFILE=$CONFIG{VARDIR}."/run/diagram.pid";
my $PID=HotSaNICparser::get_pid(0,$PIDFILE,"diagram");   # <<<--- second parameter not functional yet!
if ($PID > 0) {
  print "diagram process already running on PID $PID\nchecking if stalled...\n";
  if (-e $PIDFILE) { 
    my $runtime=time-(stat($PIDFILE))[10];
    print "process running $runtime sec\n";
    if ($runtime > 1800) {
      print "Killing probably stalled diagram process on $PID\n";
      kill 9,$PID;
      }
    else { print "seems ok - exiting normally.\n"; exit 0; }
    }
  }

open FILE,">$PIDFILE";
print FILE $$;
close FILE;

my $LOGNAME=$CONFIG{LOGDIR}."/diagram.log";

if (! -e $CONFIG{WEBDIR}) { mkdir $CONFIG{WEBDIR},0755; }

if ( ($CONFIG{DIAGRAMLOG} ne "all") && (-e $LOGNAME) ) { unlink $LOGNAME; }

chdir "./modules";
opendir DIR,".";
my @files=grep /[a-zA-Z]+/,readdir DIR;
closedir DIR;

foreach my $entry (@files) {
  if ( (-d $entry) && ($entry ne "CVS") ) {
    print "----- modules/$entry -----\n";
    if (index($CONFIG{SHOW},$entry) >= 0) {
      chdir "./$entry";
      if (-e "diagrams.pl") { system "./diagrams.pl"; } elsif (-e "diagrams") { system "./diagrams"; }
      chdir "..";
      }
    else { print "Module not in SHOW - skipping...\n"; }
    }
  }

unlink $PIDFILE;

