#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Andrew Karpow <andy@mail.tu-berlin.de>
# Licensed under GPL v3 or later

from smartcard.CardMonitoring import CardMonitor, CardObserver
from smartcard.util import toHexString
from threading import Condition
import subprocess

# a simple card observer that prints inserted/removed cards
class printobserver(CardObserver):

	def update(self, observable, (addedcards, removedcards)):
		for card in addedcards:

			SELECT_GUID= [0xFF, 0xCA, 0x00, 0x00, 0x00]
			print "+Inserted: ", toHexString(card.atr)

			try:
				card.connection = card.createConnection()
				card.connection.connect()

				# Request UID - Unique Identifier
				response, sw1, sw2 = card.connection.transmit(SELECT_GUID)

			except Exception as e:
				print str(e)
				continue

			# convert UID to hex-string and remove whitespaces
			send= toHexString(response).replace(' ', '')

			try:
				# Send UID to active window
				subprocess.Popen(['xdotool', 'type', send+'\n'])
			except OSError as e:
				print str(e)

		for card in removedcards:
			print "-Removed: ", toHexString(card.atr)


if __name__ == '__main__':
	cardmonitor= CardMonitor()
	cardobserver= printobserver()
	cardmonitor.addObserver(cardobserver)

	try:
		c= Condition()
		c.acquire()
		c.wait()
	except KeyboardInterrupt as e:
		cardmonitor.deleteObserver(cardobserver)

