#!/bin/bash

EXPIRETIME=$((12*60*60))
LSUSB=/sbin/lsusb


touch knowndevices
touch herelist
> lastdevice;

function notifyothers(){
	name=$1
	event=$2
	
	# syndication
	echo $name:$event >> syndication
}
function herelist(){
	name=$1
	inout=$2
	if [[ "$inout" == "in" ]]; then
		{ cat herelist; echo "$name"; } | sort -u > .herelist
		mv .herelist herelist
		echo
	fi
	if [[ "$inout" == "out" ]]; then
		grep -v "$name" herelist > .herelist
		mv .herelist herelist
	fi
}

function handledevice(){
	device=$1
	# check if unknown
	if grep $DEVICE -q knowndevices; then
		name=$(grep $DEVICE knowndevices|cut -c 42-)
		echo "Welcome to the Metalab, $name!"
		# Welcome sound or something
		# Maybe speak the line above
		
		notifyothers $name "entered"
		herelist $name "in"
		
		echo "You have been added to the here-list."
		echo 
		
		line=""
		read -t 5 -p "If you wanted to logout instead, press o: (this will go away after 5 sec)" line
		if [[ "$line" == "o" ]]; then
			notifyothers $name "left"
			herelist $name "out"
			
			echo "Logged you out. Bye!"
		else
			echo 
		fi
	else
		echo "Hey! A new device!"
		echo 
		echo -n "Do you want to register it? [y/n] "
		line=""
		read -t 10 line
		if [[ "$line" == "y" ]]; then
			echo -n "Enter your name or nickname: "
			line=""
			read -t 10 line
			if [[ "$line" != "" ]]; then
				echo $DEVICE $line >> knowndevices
				echo "Hi, $line! "
				echo "The device has been added."
				echo "Reinsert if you want to log in."
			fi
		else
			echo "Ok then."
		fi
	fi
}

function cleanuproutine(){
	while sleep 60; do
		# cleanup routine:      v this looks funny ;-)
		ls ???????????????????????????????????????? 2>/dev/null| while read DEVICE; do
			TIMEDIFF=$(($(date +%s) - $(head -n 1 $DEVICE)))
			if [ $(($TIMEDIFF > $EXPIRETIME)) == "1" ]; then
				rm $DEVICE; 
				name=$(grep $DEVICE knowndevices|cut -c 42-)
				notifyothers $name "left"
				herelist $name "out"
			fi
		done
	done
}

cleanuproutine &

sudo tail -s 0.3 -n 0 -f /var/log/messages | 
#grep --line-buffered "kernel: usb .* new" -E | 
grep --line-buffered "configuration #[0-9]* chosen" -E | 
while read line; 
do 
	DEVICE=""
	$LSUSB | cut -c 24-33 | grep -v 0000:0000 | 
	grep -v 03f0:171d | # internal usb devices
	while read line; do 
		DEVICE=$( \
			$LSUSB -d $line -v 2>/dev/null | 
			grep "id?(Serial|Product|Manufactorer|Vendor)" -Ei |
			sha1sum |
			grep -Eo '[0-9a-f]*' 
		)
		date +%s > $DEVICE
		echo $DEVICE > lastdevice
	done
done &

while true; do
	clear 
	echo "Welcome to Metalab!"
	echo
	echo "Metalabbers here: "
	echo "-------------------"
	cat herelist
	echo 
	echo "Plug in your USB device!"
	
	DEVICE=$(tail -n 1 lastdevice)
	if [[ $DEVICE != "" ]]; then
		handledevice $DEVICE
		> lastdevice
	fi
	sleep 1
done 

kill %1
kill %2
wait

