#!/usr/bin/env python
#
#  dpm-sql-file-to-dpns.py
#  gridpp-dpm-tools
#
#  Created by Sam Skipsey on 18/05/2010.
#  Copyright (c) 2010 University of Glasgow. All rights reserved.
#  This file is released under the BSD licence

__author__ = 'Samuel C Skipsey'
__date__ = 'May 2010'
__version = 0.2

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


import sys
import os
import string
import getpass
import MySQLdb
import gridpp_dpm

def main():
	if (len(sys.argv) < 2) or (sys.argv[1] == '-h'):
		print "Incorrect number of arguments: at least one pfn must be specified!"
		print "Usage: " + sys.argv[0] + " server:filepath [server:filepath]"
		sys.exit()
	
	#now sanity check the argument so it can't do any harm to the database
	# unless the driver does this for us?
	
	try:
		dpminfopath = os.environ['LCG_LOCATION'].rstrip('/') + '/etc/DPMINFO'
	except:
		dpminfopath = '/opt/lcg/etc/DPMINFO' #CONFIG, not INFO, because the CONFIG user has dpm_db rights
	try:	
		dpminfo = file(dpminfopath)
	except:
		print 'No DPMINFO or DPMCONFIG file found: cannot guess password for database ;)'
		sys.exit(1)
	(up,hd) = dpminfo.readline().split('@',1)  
	(u,p) = up.split('/',1)
	
	try:
		(h,d) = hd.split('/',1)
		d=d.rstrip()
	except:
		h=hd.rstrip()
		d='cns_db'
	
	for sfn in sys.argv[1:]:
		if valid_sfn(sfn):
			sfn_lookup(h,u,p,d,sfn)

def valid_sfn(sfn):
	value = True
	try:
		#check that the *form* of the sfn is fine: server:slashseparatedpath
		(server, fs) = sfn.split(':')
		fspathelements = fs.split('/',1) #each of these should fail if the path is odd
		serverelements = server.split('.')
	except: #so, the sfn was bad
		value = False
		print sfn + " does not look like a valid SFN."
	return value

def sfn_lookup(h, u, p, d, sfn):
	namelist = ['']
	try:
		c = MySQLdb.connect(host=h, user=u, passwd=p, db=d.strip())
		cc = c.cursor()
		cc.execute('''
 select parent_fileid, name from Cns_file_replica JOIN Cns_file_metadata ON Cns_file_replica.fileid = Cns_file_metadata.fileid WHERE Cns_file_replica.sfn="%s"''' % sfn)

		name = ''
		(name,) = cc.fetchall() #this gets the "head" of the name
		namelist.append(str(name[1]))
		parent_fileid = name[0]
		while parent_fileid > 1:
			cc.execute('''select parent_fileid, name from Cns_file_metadata where Cns_file_metadata.fileid = %s''' % parent_fileid)
			(name,) = cc.fetchall()
			namelist.append(str(name[1]))
			parent_fileid = name[0]		
	except MySQLdb.Error, e:
		print "Error %d: %s" % (e.args[0], e.args[1])
		sys.exit (1)
	cc.close()
	c.close()
	namelist.reverse() #put entries in "right" order for joining together
	print sfn + '\t' + '/'.join(namelist)[1:] #and sfn and print dpns name (minus srm bits)

if __name__ == '__main__':
	main()
 
