#!/usr/bin/env perl
# find-device-port-linux-udev - Kaleidoscope helper tool
# Copyright (C) 2017-2018  Keyboard.io, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.

use warnings;
use strict;

use FindBin qw{$Bin};

die "Usage: $0 VID PID [-v]\n" unless @ARGV >= 2;

my $vid    = shift @ARGV;
my $pid    = shift @ARGV;
my $verbose = shift @ARGV if (@ARGV);
my $prefix = '/dev/serial/by-id/';
my @paths  = `ls $prefix`;
my %devices;
my @log;

sub debug {
   if ($verbose) {
	 print STDERR @_;
   } else {
	push @log, @_;
   }
}

sub print_warning {
    print STDERR @_;
}


debug "Looking for USB device with vid=$vid and pid=$pid\n";

for my $path (@paths) {
    chomp($path);
    debug "Examining $path\n";
    debug "  not symlink\n" unless -l $prefix . $path;
    next unless -l $prefix . $path;
    my @data = `udevadm info -q property --name=${prefix}${path}`;
    for my $line (@data) {
        chomp($line);
        my ( $key, $val ) = split( /=/, $line, 2 );
        $devices{$path}{$key} = $val;
    }
    if ( hex $devices{$path}{'ID_VENDOR_ID'} != hex $vid ) {
        debug "  ID_VENDOR_ID $devices{$path}{'ID_VENDOR_ID'} != $vid\n";
        next;
    }
    if ( hex $devices{$path}{'ID_MODEL_ID'} != hex $pid ) {
        debug "  ID_MODEL_ID $devices{$path}{'ID_MODEL_ID'} != $pid\n";
        next;
    }

    debug "  Found keyboard!\n";

    if ( $devices{$path}{'ID_MM_DEVICE_IGNORE'} ) {
        debug "  ID_MM_DEVICE_IGNORE is set - good!\n";
    }

    if ( $devices{$path}{'ID_MM_CANDIDATE'}) {
      my $rules = "$Bin/../etc/60-kaleidoscope.rules";
      print_warning <<EOWARN

WARNING: your udev rules are currently configured to suggest
that your keyboard is suitable for use by ModemManager.  This
means that there is a risk of ModemManager interfering.  To avoid
this, copy

    $rules

to /etc/udev/rules.d
EOWARN
    }

    print $devices{$path}{DEVNAME};
    exit(0);
}

#debug("ERROR: I couldn't find a USB device matching the keyboard's USB Vendor and Device IDs\n");
#print_warning(join("\n",@log));