#!/usr/bin/python
# Copyright (c) Members of the EGEE Collaboration. 2004. 
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.  
#
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
#
#     http://www.apache.org/licenses/LICENSE-2.0 
#
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License.
# get information from pbs/torque LRMS, spit it out in uniform format


import sys
import getopt
import time

from TorqueInfoUtils import PBSNodesHandler
from TorqueInfoUtils import QStatHandler

def usage():
    print "Usage: lrmsinfo-pbs [-i <input_file>]"
    print "  input_file : optional text file containing 'qstat -f' output"

class StreamContainer:

    def __init__(self, stream):
        self.stream = stream
        
    def append(self, table):
        self.stream.write(str(table) + "\n")

def main():
    try:
        infile = None
        
        opts, args = getopt.getopt(sys.argv[1:], "i:", ["input="])
        for optName, optValue in opts:
            if optName in ("-i", "--input"):
                infile = optValue
        
        ncpu, freecpu = PBSNodesHandler.parse()
        sys.stdout.write("nactive      %d\n" % ncpu)
        sys.stdout.write("nfree        %d\n" % freecpu)
        # timestamp refers to UTC
        sys.stdout.write("now          %d\n" % int(time.time() + time.timezone))
        #
        # TODO verify schedCycle
        #
        sys.stdout.write("schedCycle   26\n")

        
        sContainer = StreamContainer(sys.stdout)
        QStatHandler.parse(sContainer, infile)        

    except getopt.GetoptError:
        print sys.argv[0] + ": error parsing command line\n"
        usage()
        sys.exit(2)
    except:
        etype, evalue, etraceback = sys.exc_info()
        sys.excepthook(etype, evalue, etraceback)
        sys.exit(3)




if __name__ == "__main__":
    main()


