#! /usr/bin/env python2
# $Id: dpm-list-disk,v 1.1 2008/10/21 08:47:05 gcowan Exp $

__author__ = 'Greig A Cowan, Sam Skipsey'
__date__ = 'April 2008'
__version__ = 0.2

'''List DPNS entries for replicas on a DPM filesystem.'''

import sys
try:
    import dpm
except:
    print 'Failed to import dpm API. Check your $PYTHONPATH. If this is correct, Please check the bitness of your system libraries - it may be that you have 64bit python and 32bit DPM.'
    sys.exit(1)

from optparse import OptionParser

def main():

    usage = '''usage: %prog [options]

    This allows you to list the replicas on disk from the DPM head node
    without having to log onto the pool nodes. You can use the command line
    options to pick out the filesystem you are interested in.'''

    parser = OptionParser( usage = usage)
    parser.add_option('-f', '--fs', dest='fs', 
                      help='Specify filesystem of interest.')
    parser.add_option('-s', '--server', dest='server', 
                      help='Specify server of interest.')
    parser.add_option('-p', '--pool', dest='pool',
                      help='Specify pool of interest.')
    parser.add_option('-o', '--ordered', dest='order', action='store_true', help="Sort list by filesize")
    (options, args) = parser.parse_args()

    if len(args) > 0:
        parser.error("incorrect number of arguments")
        exit(1)

    listp = dpm.dpns_list()
    flag = dpm.CNS_LIST_BEGIN

    num_replicas=0
    if (options.order is True):
        filelist = []
        statg = dpm.dpns_filestatg()
        while(1):
            res = dpm.dpns_listreplicax(options.pool, options.server, options.fs, flag, listp)
            flag = dpm.CNS_LIST_CONTINUE
            if res == None:
			    break;
            else:
                res2 = dpm.dpns_statr(res.sfn, statg)
                if res2 == None:
                    break;
                else:
                    filelist.append((res.sfn, res.fileid, statg.filesize))
        filelist.sort(lambda x, y: cmp(y[2], x[2])) #or equivalent sort, on res2.filesize, descending
        for i in filelist:
            print "Replica:", i[0], str(i[1]), str(i[2])
            num_replicas = num_replicas +1
    else:
        while(1):
            res = dpm.dpns_listreplicax(options.pool,
                                    options.server,
                                    options.fs,
                                    flag,listp)
        
            flag = dpm.CNS_LIST_CONTINUE
        
            if res == None:
                break
            else:
                print "Replica:", res.sfn, str(res.fileid)
                num_replicas = num_replicas + 1
            
    dpm.dpns_listreplicax(options.pool,
                          options.server,
                          options.fs,
                          dpm.CNS_LIST_END,
                          listp)

    print "Found " + str(num_replicas) + " replica(s)"
    
if __name__ == '__main__':
         main()
