/*---------------------------------------------------------------------------------
Name               : check_usb.c
Author             : Marvin Raaijmakers
Description        : For checking if the keyboard is connected via USB
Date of last change: 20-Jul-2007
History            : 20-Jul-2007 Created this file

    Copyright (C) 2007 Marvin Raaijmakers

    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; either version 2
    of the License, or any later version.
    
    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, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

    You can contact me at: marvinr(at)users(dot)sf(dot)net
    (replace (at) by @ and (dot) by .)
-----------------------------------------------------------------------------------*/
#define _GNU_SOURCE
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <dirent.h>

#include <linux/input.h>

#include <keytouch-init.h>

#define EVDEV_DIR "/dev/input/"

static int always_true (const struct dirent *file);

int
always_true (const struct dirent *file)
{
	return (TRUE);
}

Boolean
check_usb_keyboard (KTKeyboard *keyboard)
/*
Input:
	keyboard - Contains the vendor and product ID of the keyboard
Returns:
	TRUE if there is an event device with the same vendor and product ID as
	in 'keyboard'.
*/
{
	struct dirent **file_list;
	int num_files, count;
	char *orig_wd;
	Boolean keyboard_found;
	unsigned short id[4];
	int fd;
	
	keyboard_found = FALSE;
	if (keyboard->vendor_id)
	{
		orig_wd = get_current_dir_name();
		if (orig_wd)
		{
			chdir (EVDEV_DIR);
			num_files = scandir (".", &file_list, always_true, alphasort);
			if (num_files >= 0)
			{
				for (count = 0; count < num_files && !keyboard_found; count++)
				{
					fd = open(file_list[count]->d_name, O_RDONLY);
					/* If the event device was successfully opened */
					if (fd >= 0)
					{
						ioctl (fd, EVIOCGID, id); /* Read the ID's */
						keyboard_found = (keyboard->vendor_id == id[ID_VENDOR] &&
						                  keyboard->product_id == id[ID_PRODUCT]);
						close (fd);
					}
				}
				free (file_list);
			}
			chdir (orig_wd);
		}
	}
	return keyboard_found;
}
