import os
import sys
import time
import logging
import pprint

from maestro.rpcclient import Session
from optparse import OptionParser

__all__ = []
__version__ = 0.1
__date__ = '2012-11-14'
__updated__ = '2012-11-14'

DEBUG = 0
TESTRUN = 0
PROFILE = 0

def main(argv=None):
    '''Command line options.'''
    program_name = os.path.basename(sys.argv[0])
    program_version = "v0.1"
    program_build_date = "%s" % __updated__
 
    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
    #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse
    program_longdesc = '''''' # optional - give further explanation about what the program does
    program_license = "Copyright (c) 2015 InWorldz Inc. All Rights Reserved. Released under the Apache 2.0 License"

    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
        
        parser.add_option("-p", "--password", dest="password", help="The password to use when connecting to the remote agent [default: %default]")
        parser.add_option("-u", "--username", dest="username", help="The username to use when connecting [default: %default]")
        parser.add_option("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %default]")        
        # set defaults
        parser.set_defaults(password="", username="", verbose=1)
        
        # process options
        (opts, args) = parser.parse_args(argv)
        
        if opts.verbose > 0:
            print("verbosity level = %d" % opts.verbose)
  
        # Set up logging
        logging.basicConfig(level=logging.DEBUG)
                     
        session = Session('http://1192.168.3.11:12089/')
        sessionid = session.api.login_with_password(opts.username, opts.password)
                
        hosts = session.api.RegionHost.get_all()
        pprint.pprint(hosts)
        
        host = hosts[0]

        print "shutting down regions"
        regions = session.api.Region.get_all()
        
        for region in regions:
            print session.api.Region.Shutdown(region, 60)
    
        print "shutting down grid services"
        user_servers = session.api.UserServer.get_all()
        for user_server in user_servers:
            print session.api.UserServer.Shutdown(user_server, 60)
            
        msg_servers = session.api.MessagingServer.get_all()
        for msg_server in msg_servers:
            print session.api.MessagingServer.Shutdown(msg_server, 60)                    
        
        grid_servers = session.api.GridServer.get_all()
        for grid_server in grid_servers:
            print session.api.GridServer.Shutdown(grid_server, 60)
                    
        print "Completed"       
        
        session.api.session.logout()
        
    except Exception, e:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2

if __name__ == "__main__":
    if DEBUG:
        sys.argv.append("-h")
        
    if TESTRUN:
        import doctest
        doctest.testmod()
        
    if PROFILE:
        import cProfile
        import pstats
        profile_filename = '_profile.txt'
        cProfile.run('main()', profile_filename)
        statsfile = open("profile_stats.txt", "wb")
        p = pstats.Stats(profile_filename, stream=statsfile)
        stats = p.strip_dirs().sort_stats('cumulative')
        stats.print_stats()
        statsfile.close()
        sys.exit(0)

    sys.exit(main())


