#! /usr/bin/env python
# 
# This file is released under the BSD licence.

__author__ = 'Greig A Cowan, Samuel C Skipsey'
__date__ = 'April 2009'
__version = 0.2


'''List physical files in a space token'''


import sys
import os
from optparse import OptionParser
import string
import getpass
import MySQLdb
import gridpp_dpm

def main():
	parser = OptionParser(
		usage = 'usage: %prog')
	parser.add_option('--st', dest='st',default='',
			help='Specify a space token description')
 
	parser.add_option('--dpns', dest='dpns',default=False, action="store_true", help="Output DPNS names rather than PFNs")
	(options, args) = parser.parse_args()
   
	if len(args) > 1:
		parser.error("incorrect number of arguments")
	
	(c,cc,dpmdb) = gridpp_dpm.MySQLConnect(True)

	try: #This will lookup *everything* if a spacetoken isn't specified. I should make spacetokens args not options.
		cc.execute('''
 select Cns_file_replica.sfn, Cns_file_replica.fileid from Cns_file_replica join %(dpm_db)s.dpm_space_reserv on %(dpm_db)s.dpm_space_reserv.s_token = Cns_file_replica.setname where %(dpm_db)s.dpm_space_reserv.u_token="%(st)s"''' % {"st": options.st, "dpm_db":dpmdb})

		results = cc.fetchall()
	except MySQLdb.Error, e:
		print "Error %d: %s" % (e.args[0], e.args[1])
		sys.exit (1)
	for line in results:
		try: #This is a fix for Python-MySQL 1.2.1 and 1.2.3 (1.2.1 returns a c array, which needs string conversion)
			l = line[0].tostring()
		except:
			l = line[0]
		if options.dpns: #Lookup the fileid for the DPNS name
			print gridpp_dpm.fileid_lookup(cc,line[1])
		else:
			print l
	cc.close()
	c.close()
if __name__ == '__main__':
	main()
 
