#!/usr/bin/env python

import SoftLayer.API
from zenjsonclient import router, ZenJsonClientError
from sets import Set
from time import sleep
import sys

###
DOMAIN_TO_APPEND = ""
if (len(sys.argv) == 2 ):
    print sys.argv[1]
    DOMAIN_TO_APPEND = sys.argv[1]
    if (DOMAIN_TO_APPEND[0] != "."):
        DOMAIN_TO_APPEND="."+DOMAIN_TO_APPEND
###

api_username = 'set me'
api_key = 'set me'

client = SoftLayer.API.Client('SoftLayer_Account', None, api_username, api_key)

object_mask = {
    'hardware' : {
        'operatingSystem' : {
            'passwords' : {},
            },
        'networkComponents' : {},
        'datacenter' : {},
        'processorCount' : {},
        }
}

client.set_object_mask(object_mask)
hardware = client.getHardware()

output_list = []
for eachDev in hardware:
    ip=""
    hostname=""
    loc=""
    if ("privateIpAddress" in eachDev.keys()):
        ip=eachDev["privateIpAddress"]
    if ("hostname" in eachDev.keys()):
        hostname=eachDev["hostname"]
    if ("datacenter" in eachDev.keys()):
        loc=eachDev["datacenter"]
    print "IP: %s, HOSTNAME: %s, LOCATION: %s" % (ip,hostname,loc)
    output_list.append({
        "IP": ip,
        "HOSTNAME": hostname,
        "LOCATION": loc
    })

print "Got some data from softlayer:"
print repr(output_list)

'''output_list = eval(open("output.txt","r").read())'''
########################################################################################################################
#Injector part
########################################################################################################################

#Fake adapter
srcdata = output_list
for each in srcdata:
    each['HOSTNAME']+=DOMAIN_TO_APPEND
print "SOURCE DATA:"
print srcdata
print '\n\n\n'

#Step 1: Get the list of locations in the zenoss
resp = router.device.getLocations()
zen_locations_dict_list = resp.result["locations"]
zen_locations_list = []
for each in zen_locations_dict_list:
    if ('name' in each.keys()):
        nm = each['name']
        if (nm[0] == "/"):
            nm=nm[1:]
        zen_locations_list.append(nm)

print "Locations found in zenoss:"
for each in zen_locations_list:
    print "\t",each
print "\n"

#Step 2: Get the list of locations from source data
src_locations_list = Set()
for each in srcdata:
    if ('LOCATION' in each.keys()):
        if ('name' in each['LOCATION'].keys()):
            src_locations_list.add(each['LOCATION']['name'])

print "Locations found in the source file:"
for each in src_locations_list:
    print "\t",each
print "\n"

#Step 3: Determine which locations are missing in zenoss
zen_locations_set = Set()
for each in zen_locations_list:
    zen_locations_set.add(each)

src_locations_set = src_locations_list

locations_difference = src_locations_list - zen_locations_set
if (len(locations_difference)):
    print "These locations from source data are missing in zenoss:"
    for each in locations_difference:
        print "\t",each

#Step 4: Add missing locations to zenoss
for each_location in locations_difference:
    resp = router.device.addLocationNode(type='organizer', contextUid='/zport/dmd/Devices/Locations', id=each_location)
    if (resp.result['success'] == True):
        print "Succesfully added new location \"",each_location,"\" to zenoss."

#Step 5: Get hostnames/devices from zenoss
resp = router.device.getDevices(uid="/zport/dmd/Devices", sort="name", limit=10000000)
dev_response = resp.result['devices']

#Step 6: Collect devices hostnames from response and source data
dev_response_hostnames_set = Set()
for each in dev_response:
    if ('name' in each):
        dev_response_hostnames_set.add(each['name'])

print "Hostnames found in zenoss:"
for each in dev_response_hostnames_set:
    print "\t",each
print


dev_source_hostnames_set = Set()
for each in srcdata:
    if ('HOSTNAME' in each.keys()):
        dev_source_hostnames_set.add(each['HOSTNAME'])

print "Hostnames found in source data:"
for each in dev_source_hostnames_set:
    print "\t",each