#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Device::SerialPort qw( :STAT );

#
# Script made to print something to avoid funny chars on some printers
#

my $printers_started = 0;
my $is_inactive = 0;
my %devices = ();

open(F, "< /opt/pos/etc/config.ini");
while (<F>) {
  if (/<Printers>/) {
    $printers_started = 1;
  }
  elsif (/<\/Printers>/) {
    $printers_started = 0;
  }
  else {
    next if ! $printers_started;

    if (/Inactive/) {
      my( $val ) = $_ =~ /\s+(\d+)$/;
      $is_inactive = $val;
    }

    if (/Device\s+(.*?)$/) {
      $devices{$1} = 1 if $1 !~ /SCREEN/ && ! $is_inactive;
    }
  }
}
close(F);

sleep 10;

foreach my $port (keys %devices) {
  &flush_buffer( $port );
}

sub flush_buffer {
  my $port = shift;

  my $PortObj = Device::SerialPort->new($port);

  if (defined $PortObj) {
    $PortObj->baudrate(9600);
    $PortObj->parity("none");
    $PortObj->databits(8);
    $PortObj->stopbits(1);
    $PortObj->handshake("none");
    $PortObj->purge_all();
    $PortObj->lookclear();
    $PortObj->close;

    open(F, "> /tmp/print.txt");
    print F chr(0x1B).chr(0x61).1;
    print F chr(0x1B).chr(0x21).chr(0x20);
    print F "!! PRINTER OK !!\n\n";
    print F chr(0x1B).
      chr(0x21).
      chr(0x00);
    print F
      chr(0x1B).
      chr(0x64).
      chr(0x06).
      chr(0x1B).
      chr(0x69);
    close(F);

    system("cat /tmp/print.txt > $port");
  }
  else {
    print STDERR "ERROR ON PORT: $port\n";
  }
}

