#!/usr/bin/perl

use strict;
use warnings;
use IO::Socket::INET;
use Sys::Hostname;

my( $brc, $s, $i, $j, $adr, $fn, $night);
our(@ARGV);

$night=10;
$fn='tmp.dat';
# $adr='129.16.35.31';
#$adr='192.168.1.10';
$adr=inet_ntoa((gethostbyname(hostname))[4]);
print "IP: $adr\n";
#
# Compute broadcast address by
# bit-complement of subnet mask | subnet
# e.g. 255.255.255.0 -> 0.0.0.255 
#      0.0.0.255 | 192.168.1.* -> 192.168.1.255
#
# Chalmers has subnet mask 255.255.0.0
# $brc='129.16.255.255';
#
# Or use inet_ntoa(INADDR_BROADCAST), typically 255.255.255.255

$brc='192.168.1.255';

if ( $ARGV[0] ){
while ( $ARGV[0] =~ m/[-].*/ )
 {
   if ( $ARGV[0] eq '-b' ){ shift; $brc = $ARGV[0]; 
                         print "Broadcast address:    $brc\n" }
elsif ( $ARGV[0] eq '-t' ){ shift; $adr = $ARGV[0]; 
                         print "This machine address: $adr\n" }
elsif ( $ARGV[0] eq '-n' ){ shift; $night = $ARGV[0]; 
                         print "Seconds between read: $night\n" }
elsif ( $ARGV[0] eq '-h' ){
 print "USAGE:\n            udp-brc-file.pl [options] [<file>]\n\n";
 print "PURPOSE:\n";
 print "            Copy a temporary file to an UDP broadcast socket.\n";
 print "            Program creates the socket.\n";
 print "            When the file is transferred this program will remove it\n";
 print "            and wait until a new file with the same name is found again\n";
 print "            It will try for 70 seconds. If the file is still not found\n";
 print "            the program will exit.\n\n";
 print " <file>       - Default = tmp.dat\n\n";
 print "OPTIONS:\n";
 print " -b #.#.#.#   - IPv4 broadcast-address\n\n";
 print " -n #n        - wait #n seconds before renewed file detection\n\n";
exit }
shift }
if ( $ARGV[0]){ $fn = $ARGV[0] }
}

$|++;

my $sock = IO::Socket::INET->new(
           PeerPort  => 54321, 
#           PeerAddr  => inet_ntoa(INADDR_BROADCAST), 
           PeerAddr  => $brc, 
           Proto     => 'udp', 
           LocalAddr => $adr, 
           Broadcast => 1 ) 
           or die "Can't bind: $@\n";

#$s = inet_ntoa(INADDR_BROADCAST); print "Broadcast IP: $s\n";
$s = $brc; print "Broadcast IP: $s\n";

print "Start to send\n";
WH: while ( ! -r 'STOPSEND' ){
  if ( -r $fn )
    { sleep(1); open (FH,$fn); $i=0; 
      while (<FH>)
	{ chomp;  $i++; $j=$i % 10;
	  print $sock "$_\n"; 
          print "$j";
	}  
      print "\n";
      close (FH);
      `rm -f $fn`;
      sleep($night)
    }
  else
    { sleep(1);
CH:   for ($j=0;$j<70;$j++){ if ( -r $fn ){ last CH }; sleep(1) }
      print "File $fn won't re-appear\nSTOP\n"; last WH;
    }
}
close($sock);
exit
