#!/usr/bin/perl

use strict;
use warnings;
use lib "/opt/pos/lib";
use IO::Socket::Multicast;
use App::POS::Config;
use Tie::File;
use File::Slurp qw( read_file write_file );

die "Needs to be executed as root...\n" unless $ENV{USER} eq 'root';

my $port = 31101;
my $group = '225.0.0.1';
my $cfg_file = '/opt/pos/etc/config.ini';

my $cfg = App::POS::Config->new( file => $cfg_file );
my $info = $cfg->load();

$info->{STATION_NUMBER} //= 0;

if ($info->{STATION_NUMBER} eq '0') {
  print STDERR "This is station 0, aborting...\n";
  exit;
}

my $s = IO::Socket::Multicast->new( LocalPort => $port );

# Add a multicast group
$s->mcast_add($group);

my $last_server_ip = $info->{NETWORK_SERVER_IP} // "";

while (1) {
  #print STDERR "Loop...\n";

  my $server_ip = "";
  $s->recv($server_ip, 1024);

  my $software_restart = 0;

  if ($server_ip && $server_ip ne $last_server_ip) {
    print STDERR "### got new server ip or server ip changed... new one is: $server_ip\n";

    # server ip already exists, lets check it
    if (exists $info->{NETWORK_SERVER_IP}) {
      my $cnt = read_file($cfg_file) or die $!;
      $cnt =~ s/^NETWORK_SERVER_IP=.*$/NETWORK_SERVER_IP=$server_ip/m;
      write_file($cfg_file, $cnt) or die $!;
      $software_restart = 1;
    }
    # server ip doesn't exists, lets add it
    else {
      my @array;
      tie @array, 'Tie::File', $cfg_file or die $!;
      unshift @array, "NETWORK_SERVER_IP=$server_ip\n";
      $software_restart = 1;
    }

    # restart software
    if ($software_restart) {
      print STDERR "Will restart software...\n";

      if (-e "/opt/bin/kill_pos.sh") {
        system("/opt/bin/kill_pos.sh");
      } else {
        system("ps xa | grep \"/opt/pos/common/bin/pos\" | grep -v grep | awk '{ print \$1 }' | sudo xargs kill -9 2> /dev/null");
      }
    }

    $last_server_ip = $server_ip;
  }

  sleep 1;
}

