#!/bin/env python
import struct, os, fcntl, threading, sys, time
"""
	Usage:
		test.py <usbdevice i.e. sda1>
		
		This script will create a tun-device for ptp. Initialize
		using
			ifconfig tun0 192.168.1.1 pointopoint 192.168.1.2

		It will sync whenever the stick is beeing attached to the
		pc or when new packets arrive. But it's slooooooow.

		Have fun.

	License:
		Do whatever the fuck you want. I don't take any warranty.

	The packet size and ioctl call number have been found using:
		#include <stdio.h>
		#include <sys/types.h>
		#include <fcntl.h>
		#include <string.h>
		#include <sys/socket.h>
		#include <sys/ioctl.h>
		#include <linux/if.h>
		#include <linux/if_tun.h>
		int main() {
			ifreq tmp;
			memset(&tmp, 0, sizeof(tmp));
			printf("%d\n", (long)(&tmp.ifr_flags) - (long)(&tmp));
			printf("%d\n", sizeof(sockaddr) * 5 + IFNAMSIZ);
			printf("%d\n",  TUNSETIFF);
		}

		// See linux/*.h for the constant's names
"""	

try:
	USBdev = sys.argv[1]
	print "Using %s as USBdev, mounting through pmount" % USBdev
except:
	print "Usage: test.py <usbdevice>"
	sys.exit(1)

# Open tunnel
file = os.open("/dev/net/tun", os.O_RDWR)

# Tun device IOCTL
packet = struct.pack("16xb23x", 1)
fcntl.ioctl(file, 1074025674, packet) # TUNSETIFF

send = ""
sendLock = threading.RLock()

# tun->usb
def deviceData():
	global send
	while 1:
		data = os.read(file, 1024)
		data = data.ljust(1024, "\0")
		#print "tun->usb: received one packet"
		sendLock.acquire()
		send += data
		sendLock.release()
threading.Thread(target=deviceData).start()

# usb->tun and sync
def sync():
	global send
	append = False
	while 1:
		while not os.access("/dev/%s" % USBdev, os.F_OK):
			time.sleep(1)
		print "usb: found device"
		if os.system("pmount %s" % USBdev) != 0:
			print "usb: FAILED TO MOUNT!"
			time.sleep(3)
			continue

		if os.access("/media/%s/devdata" % USBdev, os.F_OK) and not append:
			input = open("/media/%s/devdata" % USBdev)
			data = input.read()
			input.close()
			os.remove("/media/%s/devdata" % USBdev)

			packets =  [ data[n:n+1024].rstrip("\0") for n in range(0, len(data), 1024) ]
			print "usb->tun: received data, %d packets" % len(packets)
			for packet in packets:
				if os.write(file, packet) != len(packet):
					print "usb->tun: NOT ALL BYTES WRITTEN!"

		sendLock.acquire()
		if len(send) > 0:
			print "tun->usb: sync to usb (%d packets)" % (len(send) / 1024)
			if append:
				output = open("/media/%s/devdata" % USBdev, "a")
			else:
				output = open("/media/%s/devdata" % USBdev, "w")
			output.write(send)
			output.close()
			send = ""
		sendLock.release()
		
		if os.system("pumount %s" % USBdev) != 0:
			print "usb: FAILED TO UNMOUNT!"
			print "usb: (critical)"
			sys.exit(0)
		print "usb: unmounted"

		append = True
		time.sleep(2)
		while os.access("/dev/%s" % USBdev, os.F_OK):
			if len(send) > 0:
				break
			time.sleep(0.5)
		if os.access("/dev/%s" % USBdev, os.F_OK):
			continue

		print "usb: device gone"
		append = False
threading.Thread(target=sync).start()

print "Use 'pkill -f test.py' to end this :P"
