#! /usr/bin/perl

use IO::Socket;
#use POSIX


while (1) {

print "Run outer watchdog loop, wait 15s\n\n";
printlog("Run outer watchdog loop, wait 15s\n\n");
sleep (15);


my $sock = new IO::Socket::INET (
                                  PeerAddr => 'localhost',
                                  PeerPort => '9333',
                                  Proto => 'tcp',
                                 );
#die "Could not create socket: $!\n" unless $sock;


#my @riclist = `/etc/pocserv/dispatch/list_rics_only`;



printlog("pocserv startup\n");


printlog("Logfile: /tmp/pocserv\n");

        # SOCKET geöffnet
        # Aktionen:
        #
        # - Admin notify
        #


        system("/etc/pocserv/adminnotify/notify Neustart \"POCSERV: Monitord client verbunden. \"");
        if ($? != -1) {
                printlog("--> Admin Notification successfully posted\n");
        }





my $oldric;
my $oldsubric;
my $oldmsg;


while (<$sock>) {


	chomp ($_);



	# SOCKET parsen
	# Verzweigen je nach Nachrichtart

	if ($_ =~ /^320/) {


		# POCSAG datagram
		# Aktionen:
		#
		# - rearm script ausführen
		# - dekodieren, ausgeben, an DISPATCH übergeben (mehrere instanzen)

	
		system("/etc/pocserv/signalguard/rearm >/dev/null 2>/dev/null");
        	if ($? != -1) {
			printlog("--> received datagram, watchdog reset\n");
		}
		my @datagram = split(/:/, $_);


		my $time=localtime($datagram[1]);
		my $timeunix=$datagram[1];
		my $ric=$datagram[3];
		my $channel=$datagram[2];
		my $subric=$datagram[4];
		my $text;


		printlog("Time <$time> ");
		#printlog("Channel <$channel> ");
		printlog("RIC <$ric> ");
		printlog("Subric <$subric> ");
		if ($datagram[5]) {
			$text=hex_to_ascii($datagram[5]);
			if ($text =~ /[a-zA-Z]+/) {
				printlog("\nText: $text\n");
			} else {
				printlog("\n");
			}
		}


		# deviation in either RIC or SUBRIC or TEXT (text only if partial match does not work)
		if (($ric ne $oldric) || ($subric ne $oldsubric) || ($text !~ /($oldmsg)/)) { 
		
			# dispatch
			system("/etc/pocserv/dispatch/dispatcher $ric \"$text\" $timeunix $subric");


			# remember old values
			$oldric = $ric;
			$oldsubric = $subric;
			$oldmsg = $text;

		} else {
		printlog ("Suppressed duplicate message\n");
		}


	}

	else {

		printlog("$_\n");

	}



}

close($sock);


}


# SUBS ###########################################################

sub hex_to_ascii ($)
{
	## Convert each two-digit hex number back to an ASCII character.
    	(my $str = shift) =~ s/([a-fA-F0-9]{2})/chr(hex $1)/eg;
#	$str = decode("iso-8859-1", $str);
    	return $str;
}


sub printlog ($)
{
	my $text = shift();
	print $text;
	open(LOGFILE,">>/tmp/pocserv");
	print LOGFILE $text;
	print LOGFILE "\n";
	close(LOGFILE);
}
