#!/usr/bin/perl

use strict;
use IO::Socket;


print "USR tester\n";
$host='192.168.101.13';

die "usage: setlx lx eol 115\n"
  if (scalar @ARGV < 3);

my ( $line, $lx, $script, $scr, $ln );
$script = $ARGV[1];

$lx = IO::Socket::INET -> new (Proto => "tcp", PeerAddr => $ARGV[0], PeerPort => "telnet") or die ("Connect to lx: $!\n");

my ( $configdir, $scriptsfile, $datafile, $dt, %data );
$configdir = "/usr/local/etc/setlx";
$scriptsfile = "scripts";
$datafile = "data";

for $dt ("COMMON", $ARGV[2]) {
  open (data, "$configdir/$datafile") or die "Open: $! $configdir/$datafile\n";
  my ( $fill, $param, $val );
  while ($line = <data>) {
    chomp $line;
    if (($fill, $param, $val) = ($line =~ /^(\[$dt\])[ \t]*([^ ]*)[ \t]*([^ ]*)/)) {
      $data { $param } = $val;
    };
  };
  close data;
};

$SIG{ALRM} = \&close_all;

open (scripts, "$configdir/$scriptsfile") or die "Open: $! $configdir/$scriptsfile\n";
while ($line = <scripts>) {
  chomp $line;
  if ($line =~ s/^(\[$script\])[ \t]*(.*)/$2/i) {
    my ( $i );
    for $i (keys %data) {
      $line =~ s/#$i#/$data{$i}/i
    };
    alarm 3;
    print $lx "$line\n";
    print "$line\n";
  };
};
close scripts;

while ($line = <$lx>) {
  print $line;
  alarm 3;
};

$lx -> close ();

sub close_all {
  $lx -> close ();
  exit;
};
