"""
This is a little script that's supposed to faciliate the copying of
the contents of many CDs to a given directory.

Maidanak prototype...
"""

This is just for documentation.  Use the copying helpers now.

import os, fcntl, shutil, sys, time

CD_devpath="/dev/cdrom"
CD_autopath="/auto/cdrom"

def cdrom_eject(devpath=CD_devpath):
	"""ejects the current CD.
	"""
	cd = 0
	try:
		while 1:
			time.sleep(0.5)
			try:
				cd = os.open(devpath, os.O_RDONLY|os.O_NONBLOCK)
				fcntl.ioctl(cd, 0x5309)
				break
			except IOError:
				if cd>0:
					os.close(cd)
				cd = 0
				print "CD still busy, retrying in 10 secs..."
				time.sleep(10)
	finally:
		if cd>0:
			os.close(cd)


def waitforcd(devpath=CD_devpath):
	"""waits for the CD tray to be closed.
	
	It waits for the changed status as opposed to the tray status as
	I found the tray status reporting to be unreliable
	"""
	wait_timeout = 0
	print "Waiting for CD",
	while 1:
		try:
			cd = os.open(devpath, os.O_RDONLY|os.O_NONBLOCK)
			if cd<0:
				rtval = 1
			else:
				rtval = fcntl.ioctl(cd, 0x5325, 0)
			if rtval==0:
				break
			wait_timeout = wait_timeout+1
			if wait_timeout>50:
				fcntl.ioctl(cd, 0x5309)
				wait_timeout = 0
			time.sleep(1)
			print ".",
		finally:
			if cd>0:
				os.close(cd)
	print


def readcds(destBase, srcCount):
	if not os.path.exists(destBase):
		os.mkdir(destBase)
	while 1:
		dest = os.path.join(destBase, "cd%03d"%srcCount)
		print "Now writing to", dest
		try:
			os.listdir(CD_autopath) # mount the thing first
			shutil.copytree(CD_autopath, dest)
		except (shutil.Error, KeyboardInterrupt):
			print ("Copying failed or interrupted.  Removing destination %s."
				"  Try again.")%(
				dest)
			shutil.rmtree(dest)
			sys.exit(1)
		time.sleep(4)
		cdrom_eject()
		waitforcd()
		srcCount += 1


def getLastIndex(targetDir):
	try:
		return max([int(n[2:]) for n in os.listdir(targetDir)])
	except IOError:
		return 0

if __name__=="__main__":
	destdir = "/home/gavo/inputs/maidanak/raw"
	startIndex = getLastIndex(destdir)+1
	readcds(destdir, startIndex)
