#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use FindBin qw( $Bin );
use lib "$Bin/../../lib";
use File::Copy qw( copy move );
use App::POS::Config;
use App::POS::Machine::Station;
use App::POS::Machine::Server;
use App::POS::Utils qw( translate );

my $cfg = App::POS::Config->new( file => "/opt/pos/etc/config.ini" );
my $info = $cfg->load_fixed();

my $machine = undef;

if (exists $info->{STATION_NUMBER} && $info->{STATION_NUMBER} > 0) {
  $machine = App::POS::Machine::Station->new( config => $cfg );  
}
else {
  $machine = App::POS::Machine::Server->new( config => $cfg );  
}

my @devices = ( 'device1', 'device2', 'device3', 'device4', 'device5' );

my $auto_discover = shift;

if (defined $auto_discover) {
  while (1) {
    my $found = 0;

    print STDERR "------------------------------------------------\n";
    print translate($machine, "INSIRA O DISPOSITIVO USB E PRIMA <ENTER>") . "\n";
    my $enter = <STDIN>;

    print translate($machine, "POR FAVOR AGUARDE...") . "\n";
    sleep 3;

    my $devices_original = read_devices();

    print translate($machine, "DESLIGUE O DISPOSITIVO USB E PRIMA <ENTER>") . "\n";
    $enter = <STDIN>;

    my $devices_after = read_devices();

    foreach my $k (keys %$devices_original) {
      if (! exists $devices_after->{$k}) {
        $found = $k;
        print translate($machine, "DISPOSITIVO ENCONTRADO") . " - $k\n";
      }
    }

    if (! $found) {
      print translate($machine, "NÃO FOI ENCONTRADO NENHUM DISPOSITIVO, VAMOS COMEÇAR DE NOVO...") . "\n";
    }
    else {
      my $idx = 1;

      foreach my $l (@devices) {
        print $idx.") ".$l."\n";
        $idx++;
      }

      print translate($machine, "QUAL O DISPOSITIVO VIRTUAL A USAR") . "? [1-5]\n";
      my $id = <STDIN>;
      chop($id);

      if ($id !~ /^\d+$/) {
        print translate($machine, "INVÁLIDO") . "\n";
        sleep 2;
        exit;
      }

      my $dev_name = $devices[$id-1];

      if (! defined $dev_name) {
        print translate($machine, "INVÁLIDO") . "\n";
        sleep 2;
        exit;
      }

      my( $vendor, $product ) = split /:/, $found;

      open(F, "> /etc/udev/rules.d/30-usb-custom.rules");
      print F "SUBSYSTEMS==\"usb\", ATTRS{idVendor}==\"$vendor\", ATTRS{idProduct}==\"$product\", SYMLINK+=\"$dev_name\", MODE==\"0777\"\n";
      close(F);

      system("udevadm trigger --action=add");

      print translate($machine, "SUCESSO") . "\n";
      sleep 2;

      exit;
    }
  }

  exit;
}

my $cmd = 'lsusb | grep -v "Linux Foundation"';
my @l = `$cmd`;
my @add_devices = ();

while(1) {
  my %map = ();
  my $idx = 1;

  foreach my $l (@l) {
    chop($l);
    my @a = split /\s/, $l;
    my $id = $a[5];
    my @b = splice(@a,6,-1);
    my $desc = join(" ", @b);
    print $idx.") ".$id." #$desc#\n";

    $map{$idx} = $id;

    $idx++;
  }

  print "\nID NUMBER: ";
  my $id = <STDIN>;
  chop($id);

  if ($id eq '') {
    last;
  }

  if ($id !~ /^\d+$/) {
    print "INVALID!\n";
    exit;
  }

  if (! exists $map{$id}) {
    print "INVALID!\n";
    exit;
  }

  my $id_str = $map{$id};

  print "\n\n";

  $idx = 1;
  %map = ();

  foreach my $l (@devices) {
    print $idx.") ".$l."\n";
    $map{$idx} = $l;
    $idx++;
  }

  print "\nDEVICE: ";
  $id = <STDIN>;
  chop($id);

  if ($id !~ /^\d+$/) {
    print "INVALID!\n";
    exit;
  }

  if (! exists $map{$id}) {
    print "INVALID!\n";
    exit;
  }

  my $device_str = $map{$id};

  push @add_devices, [ $id_str, $device_str ];
}

die "NO DEVICES TO ADD..." unless scalar @add_devices;

open(F, "> /etc/udev/rules.d/30-usb-custom.rules");

for (@add_devices) {
  my( $dev_id, $device ) = @$_;
  my( $vendor, $product ) = split /:/, $dev_id;
  print F "SUBSYSTEMS==\"usb\", ATTRS{idVendor}==\"$vendor\", ATTRS{idProduct}==\"$product\", SYMLINK+=\"$device\", MODE==\"0777\"\n";
}

close(F);

system("udevadm trigger --action=add");


sub read_devices {
  my $idx = 0;
  my $cmd = 'lsusb';
  my @l = `$cmd`;
  my %map = ();

  foreach my $l (@l) {
    chop($l);
    my @a = split /\s/, $l;
    my $id = $a[5];
    my @b = splice(@a,6,-1);
    my $desc = join(" ", @b);
    #print $idx.") ".$id." #$desc#\n";

    $map{$id} = $idx;
  }

  #print STDERR Dumper(\%map);

  return \%map;
}
