#!/usr/bin/env python

# author: Fred Laine

# disable SSL verification
import ssl
import json
import requests
import urllib3
from pprint import pprint as pp

#disable ssl warnings
urllib3.disable_warnings()

# the configuration elements per switch in arista.conf
mcs_config_block = ""

# File containing the switches serial numbers \n terminated. In the same directory as this .py code.
hostnameFile = 'switchSerialList.txt'

# Name of the .conf file generated by this script.
arista_conf = 'arista.conf'

# Interface name to use to find the ip address used by mcs and used for grpc connection back to the switch
interfaceName = 'Loopback0'


try:
    ssl._create_default_https_context = ssl._create_unverified_context
except Exception as e:
    print("Exception in SSL creation")
    pprint (e)
    raise e


# cvp ip url, very important
cvpIP = ''

headers = { 'Content-Type': 'application/json'}

# login API - you will need to login first
# and save the credentials in a cookie
loginURL = "/web/login/authenticate.do"

# cvp user and password
USER = ''
PASSWORD = ''



# First we have to login and save the session in a cookie
# which can be later referred to make API calls
try:
    response = requests.post(cvpIP+loginURL,json={'userId':USER,'password':PASSWORD},headers=headers,verify=False)
    cookies = response.cookies
except Exception as e:
    print("Exception in post")
    pprint (e)
    raise e


#rest API uri
restAPI = 'api/v1/rest/'


#path = "/Sysdb/ip/config/ipIntfConfig/Loopback0"
# Aeris Analytic path section, before the serial number
prepath = 'analytics/Devices/'

# Aeris Analytic path section, after the serial number
postpath = '/versioned-data/Device'

# Sysdb path for interface used to connect back to the switch (eAPI, TerminAttr and grpc) 
managementIPToUsePath = '/Sysdb/ip/config/ipIntfConfig/'+interfaceName

detailedpath = ''

try:
    #Source file object used to read switches serial numbers
    sourceFile = open(hostnameFile, 'r')

    #Destination file object used to write the mcs configuration entry
    destFile = open(arista_conf,'w')


    switchList = sourceFile.readlines()

    # iterate on all the serial numbers listed in the source file.
    for items in switchList:
        # for each lines, remove the carriage return
        item = items.replace('\n', '')

        try:
            print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n')
            # Build the Aeris analytic path for switch
            detailedpath = cvpIP+restAPI+prepath+item+postpath
            print(detailedpath)
            # Get the path content doing a get request
            response = requests.get(detailedpath,cookies=cookies, verify=False)

            versiondata = response.json()

            # Iterate in the update and look for the index that holds the hostname key
            for key in versiondata['notifications']:
                if 'hostname' in key['updates'].keys():
                    hostname = key['updates']['hostname']['value']
                    print(item+'   '+hostname)
               
            detailedpath = cvpIP+restAPI+item+managementIPToUsePath
            print(detailedpath)
            # Get the Sysdb path that has the IP to use to connect with the switch (eAPI, TerminAttr and grpc)   
            response = requests.get(detailedpath,cookies=cookies, verify=False)
            data = response.json()

            # Iterate in the update and look for the index that holds the hostname key
            for key in data['notifications']:
                if 'addrWithMask' in key['updates'].keys():
                    IPwithMask = str(key['updates']['addrWithMask']['value'])

            IP = IPwithMask.replace("/32","")
            print(hostname +'  '+IP)



            mcs_config_block = '[' + hostname + ']\n' \
                               'hostname = ' + hostname + '\n' \
                               'ip = ' + IP + '\n' \
                               'username = ' + USER + '\n' \
                               'password = ' + PASSWORD + '\n' \
                               'transport = https\n' \
                               'enable_password =\n' \
                               'grpcaddr = ' + IP + ':5910\n' \
                               'dbgrpcstatus = ok\n' \
                               'mcastappgrpcstatus = ok\n' \
                               'mainappgrpcstatus = ok\n'\
                               '\n'
            destFile.write(mcs_config_block)



        except Exception as e:
            print('EXCEPTION   '+item)
            pp(e)
            #print(item+'   '+str(versiondata['notifications'][2]['updates']['hostname']['value']))
            print versiondata

except Exception as e:
    pp(e)
    raise e
#print(loopbackIP)
finally:    
    sourceFile.close()
    destFile.close()
