#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

system("disk_rw");

my $cmd = 'lsusb | grep -v "Linux Foundation"';
my @l = `$cmd`;
my @devices = ( 'ttyUSB0', 'ttyUSB1', 'ttyUSB2', 'ttyUSB3', 'ttyUSB4' );
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("/sbin/udevadm trigger --action=add");

