#!/usr/bin/env python2
#
#  dpm-sql-dpns-by-replication.py
#  gridpp-dpm-tools
#
#  Created by Sam Skipsey on 01/04/2011.
#  Copyright (c) 2011 University of Glasgow. All rights reserved.
#  This file is licensed for use under the BSD licence.

__author__ = 'Samuel C Skipsey'
__date__ = 'April 2011'
__version = 0.1

'''List DPNS entries with more than or equal to n replicas'''


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

try:
	import MySQLdb
except:
	sys.exit("Could not import MySQLdb module. Please install the MySQL Python module.")

try: 
	import gridpp_dpm
except:
	sys.exit("Can't load gridpp-dpm module. Old version of the tools installed?, PYTHONPATH incomplete?")

def main():
	parser = OptionParser()
	parser.add_option("-n","--no_replicas",dest="n",default=2,help="Minimum number of replicas a file needs to be reported")
	(opt,args) = parser.parse_args()
	
	
#	if len(args) != 1:  #make me an OptParse
#		#we need to take in one argument, at least (the name of the disk server, and filesystem, as a single string)
#		#with an option of separate disk server and fs args (makes iteration easier)
#		#allow specification of ssh user name and auth mech?
#		#allow "only print missing files" optio
#		sys.exit("Wrong number of args")
	
	#now, try parsing the arg we got into a disk and an fs
	try:
		number = int(opt.n)
	except:
		sys.exit("Could not parse arg into a number of replications")


	(c,cc) = gridpp_dpm.MySQLConnect()

	cc.execute('''select fileid, count(*) as rep from Cns_file_replica GROUP BY
Cns_file_replica.fileid ORDER BY rep DESC''')
	fileid_list = cc.fetchall()
	for file in fileid_list:
		if int(file[1]) < int(number):
			break
		try:
			dpnsfile = gridpp_dpm.fileid_lookup(cc,file[0])
			print dpnsfile + "\t Replicas="+str(file[1]) 
		except:
			print "NOFILE\tfileid=" + str(file[0])
	cc.close()
	c.close()	



#def MySQLConnect():	
#	try:
#		dpminfopath = os.environ['LCG_LOCATION'].rstrip('/') + '/etc/DPMCONFIG'
#	except:
#		dpminfopath = '/opt/lcg/etc/DPMINFO' #CONFIG, not INFO, because the CONFIG user has dpm_db rights
#	try:	
#		dpminfo = file(dpminfopath)
#	except:
#		sys.exit('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'
#	try:
#		c = MySQLdb.connect(host=h, user=u, passwd=p, db=d.strip())
 #       	cc = c.cursor()
#	except MySQLdb.Error, e:
 #               sys.exit("Error %d: %s" % (e.args[0], e.args[1]))
  #              #sys.exit (1)
#
#	return c,cc
#
#
#def sfn_lookup(cc, fileid):
#	namelist = ['']
#	try:
#		cc.execute('''
 #select parent_fileid, name from Cns_file_metadata WHERE Cns_file_metadata.fileid = %s ''' % fileid)
#
#		name = ''
#		parent_fileid = 0L
#		p = cc.fetchone()
#		#handle zero results here by raising exception!!!
#		(parent_fileid, name) = p #this gets the "head" of the namei
#		namelist.append(str(name))
#		while parent_fileid > 1:
#			cc.execute('''select parent_fileid, name from Cns_file_metadata where Cns_file_metadata.fileid = %s''' % parent_fileid)
#			(parent_fileid, name) = cc.fetchone()
#			#the above fetchone() is a zero length tuple in the case of no results, so that should except?
#			namelist.append(str(name))
#	except MySQLdb.Error, e:
#		sys.exit("Error %d: %s" % (e.args[0], e.args[1]))
#		#sys.exit (1)
#	namelist.reverse() #put entries in "right" order for joining together
#	return '/'.join(namelist)[1:-1] #and print dpns name (minus srm bits)
#
if __name__ == '__main__':
	main()
 
