'''
from inworldz_api import Session

session = Session('http://localhost:9000/xmlrpc/RemoteAdmin')
session.login_with_password('<PASSWORD>', '<PASSWORD>')

result = session.api.Console.Command("show users")
print result

region = session.api.Region.GetByName("OpenSim Test")
print result

session.api.Region.Restart(region)

session.api.session.logout()
'''
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 provision_region(session, host, sim_name, loc_x, loc_y):
    print "provisioning region ", sim_name

    region_record = {
     'sim_name': sim_name,
     'sim_location_x': str(loc_x),
     'sim_location_y': str(loc_y),
     'owner_uuid': '00000000-0000-0000-0000-000000000000',
     'master_avatar_uuid' : '00000000-0000-0000-0000-000000000000',
     'master_avatar_first' : 'Mike',
     'master_avatar_last' : 'Chase',
     'master_avatar_pass' : '<PASSWORD>'
     } 

    region = session.api.RegionHost.ProvisionRegion(host, region_record)
    print "Region: "+ session.api.Region.get_sim_name(region) + " created"
    update_and_reconfigure_region(session, region)


def update_and_reconfigure_region(session, region):
    sim_name = session.api.Region.get_sim_name(region)
    print "Updating and Reconfiguring Region: ", sim_name
    if (sim_name == "Test2"):
        print session.api.Region.UpdateRegionToRevision(region, "3164")
    else:
        print session.api.Region.UpdateRegionToLatest(region)
    print "...Updated"
    print session.api.Region.ReconfigureRegion(region)
    print "...Reconfigured"
    
     
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://127.0.0.1:12089/')
        sessionid = session.api.login_with_password(opts.username, opts.password)
                
        hosts = session.api.RegionHost.get_all()
        pprint.pprint(hosts)
        
        for host in hosts:
            record = session.api.RegionHost.get_record(host)
            pprint.pprint(record)
            
            #provision_region(session, host, "Test2", 1000, 1001)
            #return
        
            print "Get CPU"
        
            cpu = record['Cpu']
            pprint.pprint(session.api.Cpu.get_record(cpu))
            pprint.pprint(session.api.Cpu.cpu_percent(cpu))
            pprint.pprint(session.api.Cpu.cpu_percent(cpu, 5.0, True))
            pprint.pprint(session.api.Cpu.cpu_times(cpu, True))
        
            print "Get Disk"
        
            disk = record['Disk']
            pprint.pprint(session.api.Disk.get_record(disk))
            pprint.pprint(session.api.Disk.disk_usage(disk, "/"))
            pprint.pprint(session.api.Disk.disk_io_counters(disk, True))
        
            print "Get Memory"
        
            memory = record['Memory']
            pprint.pprint(session.api.Memory.get_record(memory))
            
            print "Get Process"
        
            process = record['Process']
            pprint.pprint(session.api.Process.get_record(process))
            
            print "fetching Regions"
            
            regions = record['Regions']
            
            for region in regions:
                region_record = session.api.Region.get_record(region)
                pprint.pprint(region_record)
                
                if (session.api.Region.IsRunning(region) == False):
                    print "Not Running"
                else:  
                    print "Running, Stopping"
                    print session.api.Region.Shutdown(region)

                update_and_reconfigure_region(session, region)
                
                #print "Starting it up"
                #session.api.Region.Start(region)
                
                #if (session.api.Region.Shutdown(region) == False):
                #    session.api.Region.Terminate(region)
                #print "Terminated"

                #
                #print "Writing Configuration for slot {0}:".format(slotnum)
                #print session.api.Region.ReconfigureRegion(region)
                # 
                # Print Make a new copy
                #print "Provisioning new region"
                #region_record = session.api.Region.get_record(region)                   
                #region_record['sim_location_y'] = int(region_record['sim_location_y']) + 1
                #print region_record
                #print session.api.RegionHost.ProvisionRegion(host, region_record)
                
        
        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())



'''
from inworldz_api import Session

session = Session('http://localhost:9000/xmlrpc/RemoteAdmin')
session.login_with_password('<PASSWORD>', '<PASSWORD>')

result = session.api.Console.Command("show users")
print result

region = session.api.Region.GetByName("OpenSim Test")
print result

session.api.Region.Restart(region)

session.api.session.logout()
'''
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 provision_region(session, host, sim_name, loc_x, loc_y):
    print "provisioning region ", sim_name

    region_record = {
     'sim_name': sim_name,
     'sim_location_x': str(loc_x),
     'sim_location_y': str(loc_y),
     'owner_uuid': '00000000-0000-0000-0000-000000000000',
     'master_avatar_uuid' : '00000000-0000-0000-0000-000000000000',
     'master_avatar_first' : 'Mike',
     'master_avatar_last' : 'Chase',
     'master_avatar_pass' : '<PASSWORD>'
     } 

    region = session.api.RegionHost.ProvisionRegion(host, region_record)
    print "Region: "+ session.api.Region.get_sim_name(region) + " created"
    update_and_reconfigure_region(session, region)


def update_and_reconfigure_region(session, region):
    sim_name = session.api.Region.get_sim_name(region)
    print "Updating and Reconfiguring Region: ", sim_name
    if (sim_name == "Test2"):
        print session.api.Region.UpdateRegionToRevision(region, "3164")
    else:
        print session.api.Region.UpdateRegionToLatest(region)
    print "...Updated"
    print session.api.Region.ReconfigureRegion(region)
    print "...Reconfigured"
    
     
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://127.0.0.1:12089/')
        sessionid = session.api.login_with_password(opts.username, opts.password)
                
        hosts = session.api.RegionHost.get_all()
        pprint.pprint(hosts)
        
        for host in hosts:
            record = session.api.RegionHost.get_record(host)
            pprint.pprint(record)
            
            #provision_region(session, host, "Test2", 1000, 1001)
            #return
        
            print "Get CPU"
        
            cpu = record['Cpu']
            pprint.pprint(session.api.Cpu.get_record(cpu))
            pprint.pprint(session.api.Cpu.cpu_percent(cpu))
            pprint.pprint(session.api.Cpu.cpu_percent(cpu, 5.0, True))
            pprint.pprint(session.api.Cpu.cpu_times(cpu, True))
        
            print "Get Disk"
        
            disk = record['Disk']
            pprint.pprint(session.api.Disk.get_record(disk))
            pprint.pprint(session.api.Disk.disk_usage(disk, "/"))
            pprint.pprint(session.api.Disk.disk_io_counters(disk, True))
        
            print "Get Memory"
        
            memory = record['Memory']
            pprint.pprint(session.api.Memory.get_record(memory))
            
            print "Get Process"
        
            process = record['Process']
            pprint.pprint(session.api.Process.get_record(process))
            
            print "fetching Regions"
            
            regions = record['Regions']
            
            for region in regions:
                region_record = session.api.Region.get_record(region)
                pprint.pprint(region_record)
                
                if (session.api.Region.IsRunning(region) == False):
                    print "Not Running"
                else:  
                    print "Running, Stopping"
                    print session.api.Region.Shutdown(region)

                update_and_reconfigure_region(session, region)
                
                #print "Starting it up"
                #session.api.Region.Start(region)
                
                #if (session.api.Region.Shutdown(region) == False):
                #    session.api.Region.Terminate(region)
                #print "Terminated"

                #
                #print "Writing Configuration for slot {0}:".format(slotnum)
                #print session.api.Region.ReconfigureRegion(region)
                # 
                # Print Make a new copy
                #print "Provisioning new region"
                #region_record = session.api.Region.get_record(region)                   
                #region_record['sim_location_y'] = int(region_record['sim_location_y']) + 1
                #print region_record
                #print session.api.RegionHost.ProvisionRegion(host, region_record)
                
        
        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())



from inworldz_api import Session  session = Session('http://localhost:9000/xmlrpc/RemoteAdmin') session.login_with_password('<PASSWORD>', '<PASSWORD>')  result = session.api.Console.Command("show users") print result  region = session.api.Region.GetByName("OpenSim Test") print result  session.api.Region.Restart(region)  session.api.session.logout() Command line options. #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse # optional - give further explanation about what the program does # setup option parser # set defaults # process options # Set up logging #provision_region(session, host, "Test2", 1000, 1001) #return #print "Starting it up" #session.api.Region.Start(region) #if (session.api.Region.Shutdown(region) == False): #    session.api.Region.Terminate(region) #print "Terminated" # #print "Writing Configuration for slot {0}:".format(slotnum) #print session.api.Region.ReconfigureRegion(region) # # Print Make a new copy #print "Provisioning new region" #region_record = session.api.Region.get_record(region) #region_record['sim_location_y'] = int(region_record['sim_location_y']) + 1 #print region_record #print session.api.RegionHost.ProvisionRegion(host, region_record)