#!/usr/bin/perl

#DESCRIPTION:
#This script gets device IDs and then starts polling process for each device.
#Written by Denis Brodovich, Andrey Armyakov. 2004.

use strict;
use DBI;
use POSIX ":sys_wait_h";
require "connect.pl";
require "log.pl";

#my $pidfile="pidfile";
my %nodhash;

#open(PIDFILE,"> $pidfile") or die "Can't open pidfile: $!";
#print PIDFILE "$$";
#close(PIDFILE);

#dolog("/tmp/polling.log","polling started.",">");

#close(STDOUT);
close(STDIN);
#close(STDERR);

#Starting alarmer.
$nodhash{"-1"} = "./alarm";
#Starting cleaner.
$nodhash{"-2"} = "./cleaner";
#Starting sendpoll
if(-f "sendpoll.pl"){
	$nodhash{"-3"} = "./sendpoll.pl";
}
#Sync with Navigator system
if(-f "navigator-sync"){
    `killall navigator-sync`;
    $nodhash{"-4"} = "./navigator-sync";
}


my $dbh = satisMysqlConnect();
my @nodes;
my $query = "SELECT t2.NodeID, t2.Type FROM Nodes t1, Nodes t2 WHERE t1.NodeID = t2.ParentID AND t1.Type = 'COMPort';";
my $sth = $dbh->prepare($query);
$sth->execute();
my $line;
while ($line = $sth->fetchrow_arrayref)
{
    if($$line[1] eq "WinRadio" || $$line[1] eq "BandWinRadio") {
    }
    elsif($$line[1] eq "HP" || $$line[1] eq "BandHP") {
    }
    elsif($$line[1] eq "FS300" || $$line[1] eq "BandFS300") {
    }
    elsif($$line[1] eq "SatSpec" || $$line[1] eq "BandSatSpec") {
    }
    elsif($$line[1] eq "Decimator" || $$line[1] eq "BandDecimator") {
    }
    elsif($$line[1] eq "RFSwitch" || $$line[1] eq "RFPort") {
    }
    elsif($$line[1] eq "DemodController") {
        $nodhash{$$line[0]}="../spectrum/DemodMonitoring/banddemod"; #Script for DemodController
    }
    elsif($$line[1] eq "M200PBX") {
        $nodhash{$$line[0]}="./snmppol"; #Script for M200 ATS (PBX)
    }
    else {
	my $line2;
	$$line2[0]=$$line[0];
	$$line2[1]="";
	while(!($$line2[1] eq "Threshhold" || $$line2[1] eq "Configuration") and $$line2[0] ne ""){
	    $nodhash{$$line2[0]}="./pol"; #Script for Device
            my $query = "SELECT NodeID,Type FROM Nodes WHERE ParentID = $$line2[0];";
            my $sth = $dbh->prepare($query) || die "Can't prepare: $dbh->errstr\n";
    	    $sth->execute();
                while ($line2 = $sth->fetchrow_arrayref) {
            	if(!($$line2[1] eq "Threshhold" || $$line2[1] eq "Configuration")){
    		    $nodhash{$$line2[0]}="./pol"; #Script for Device
	    	}
	    }
	    print " [OK]...\n";
	    $sth->finish();
	}
    }
}
$sth->finish();

#Starting traffic server
if(-f "traffic-server"){
    `killall traffic-server`;
    #$nodhash{"-t sm -p 4021"} = "./traffic-server";
    #$nodhash{"-t rtms -p 4011"} = "./traffic-server";

	my %types = ("RTMSG4" => "rtms", "SmartMicro" => "sm", "SmartSensorHD" => "sshd",);

	#starting traffic-servers in specified ports
	$query = "SELECT Nodes.Type, Value, Count(*) FROM SystemConf, Nodes WHERE SystemConf.Name = 'Port' AND Nodes.NodeID = SystemConf.NodeID AND Nodes.Type IN ('SmartMicro','RTMSG4','SmartSensorHD') GROUP BY Nodes.Type, Value;";
	$sth = $dbh->prepare($query);
	$sth->execute();
	while ($line = $sth->fetchrow_arrayref)
	{
		$nodhash{"-t " . $types{$$line[0]} . " -p " . $$line[1]} = "./traffic-server";
	}
	$sth->finish();
}


my $devices = "'Ping','Controller','P3000','TERRASAT','CDM570','CDM570L','CDM600','CDM600L','CDM625', 'CDM750', 'CDM760', 'PARADISEPA', 'SSPAP400', 'MeteoDavies', 'RCP2', 'LPOD', 'Novelsat', 'CDM625A', 'VERTEXRSI7200'";

#P3000 on IP Port included
$query = "SELECT NodeID FROM Nodes WHERE Type IN (" . $devices . ");";
$sth = $dbh->prepare($query);
$sth->execute();
while ($line = $sth->fetchrow_arrayref)
{
    $nodhash{$$line[0]}="./pol"; #Script for Pinger and Controller
}
$sth->finish();

$query = "SELECT t2.NodeID, t2.Type FROM Nodes t1, Nodes t2 WHERE t1.NodeID = t2.ParentID AND t1.Type = 'IPPort' AND t2.Type NOT IN (" . $devices . ");";
#$query = "SELECT NodeID FROM Nodes WHERE Type IN ('Switch','Router','LinkStar', 'SkyWire', 'CDD564', 'AMT30', 'AMT34', 'AZ110', 'NetPerformer', 'EquicomPing3') OR Type LIKE 'SNMP%';";
$sth = $dbh->prepare($query);
$sth->execute();
while ($line = $sth->fetchrow_arrayref)
{
    $nodhash{$$line[0]}="./snmppol";
}
$sth->finish();

#traffic sensors in polling mode
$query = "SELECT NodeID FROM Nodes WHERE Type IN ('SmartSensorHD', 'RTMSG4', 'SmartMicro') AND (SELECT Value FROM SystemConf where NodeID = Nodes.NodeID and Name = 'Mode') = '1';";
$sth = $dbh->prepare($query);
$sth->execute();
while ($line = $sth->fetchrow_arrayref)
{
    $nodhash{$$line[0]}="./snmppol";
}
$sth->finish();

$query = "SELECT NodeID FROM Nodes WHERE Type IN ('Navigator');";
$sth = $dbh->prepare($query);
$sth->execute();
while ($line = $sth->fetchrow_arrayref)
{
    $nodhash{$$line[0]}="./navigator-sync";
}
$sth->finish();

$query = "SELECT NodeID FROM Nodes WHERE Type IN ('CameraAxis');";
$sth = $dbh->prepare($query);
$sth->execute();
while ($line = $sth->fetchrow_arrayref)
{
    $nodhash{$$line[0]}="./stream.sh";
}
$sth->finish();

$dbh->disconnect();

my $key;

my $count = 0;
foreach $key (keys %nodhash) {
    $count++;
}

if($count < 1) {
    print "Nothing to poll. Exiting...\n";
    exit(0);
}


my %pidhash;
foreach $key (keys %nodhash) {
    my $pid = sfork($key); 
    $pidhash{$pid}=$key;
}
  
my $kid;
while() {
    $kid = waitpid(-1,0);
    my $tempnode=$pidhash{$kid};
    delete $pidhash{$kid};
    
    my $pid = sfork($tempnode); 
    $pidhash{$pid}=$tempnode;
}


sub sfork {
    my $nodeid=shift;
    my $pid;
	while() {
		$pid = fork();
		if(defined($pid) && $pid >= 0) {
			last;
		}
		dolog("polling.log","fork failed!",">>");
		sleep(3);
	}
    if ($pid == 0)
    {	
    	exec "$nodhash{$nodeid}", split(" ","$nodeid");
    }
    return $pid;
}

