#!/usr/bin/env python
# -*- coding: utf-8 -*-

#@Author: Carl Dubois
#@Email: c.dubois@f5.com
#@Description: Deploy LTM
#@Product: BIGIQ
#@VersionIntroduced: 5.x

"""
Copyright 2017 by F5 Networks Inc.

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.
"""

import os
import sys
import base64
import string
import requests
import time

requests.packages.urllib3.disable_warnings()

try:
    import json
except ImportError:
    import simplejson as json

def get_device(config):
    ## Get a BIGIP device which application node will live.
    uri = 'https://' + config['bigiq'] + '/mgmt/shared/resolver/device-groups/cm-adccore-allbigipDevices/devices'
    response = requests.get(uri, auth=(config['iq_user'], config['iq_pass']), verify=False)
    
    for item in response.json()['items']:
        if item['address'] == config['bigip']:
            device = item['selfLink']
            break

    return device

def deploy_ltm(config, device):
    selflink=None
    print "\n==================================================================="    
    print "Deploy LTM configuration changes to BIGIP now."
    print "===================================================================\n"
    uri = 'https://' + config['bigiq'] + '/mgmt/cm/adc-core/tasks/deploy-configuration'  
    data_json = {"name":config['name'], "deviceReferences":[{"link": str(device)}]}
    response = requests.post(uri, data=str(data_json), auth=(config['iq_user'], config['iq_pass']), verify=False) 
    
    ## DEBUG ##
    print json.dumps(response.json(), default=lambda o: o.__dict__, sort_keys=True, indent=4)
    ###########
    uri_self = response.json()['selfLink'].replace('localhost', config['bigiq'])

    t=1
    if response.status_code in [200, 202]:
        print "Deploy LTM configuration task: {0} created.".format(response.json()['name'])

        while True:
            response = requests.get(uri_self, auth=(config['iq_user'], config['iq_pass']), verify=False)
            if response.json()['status'] == 'FINISHED':
                print "Deploy task status is FINSIHED."
                return True
            elif response.json()['status'] == 'FAILED':
                print "Deploy task status FAILED."
                print "ERROR: {0}".format(response.json()['errorMessage'])
                return False
            else:
                print str(t) + " sec - {0}".format(response.json()['currentStep'])
                time.sleep(1)
                t+=1
                continue

        return True
    else:
        print "INFO: {0}".format(response.json('message'))
        return False
    
if __name__ == '__main__':
    #==========================
    # Help
    #==========================
    config={}
    import argparse

    parser = argparse.ArgumentParser(description='List all virutals and devices each live on.')
    parser.add_argument('--config', type=str, help='Configuration, IQ-IP address, user, pass.')

    args = parser.parse_args()
    
    #==========================
    # Read config file
    #==========================    
    file = args.config
    
    infile = open (file, 'r')
    for line in infile:
        (key, val) = line.split(' = ')
        config[str(key)] = val.strip('\n')
        
    #==========================
    # Get Device
    #==========================
    device = get_device(config)
    time.sleep(1)

    #==========================
    # Deploy LTM
    #==========================
    result_ltm = deploy_ltm(config, device)
    time.sleep(1)

    if result_ltm == True: 
        print '\nSUCCESS: - COMPLETE.\n'
    else:
        print '\nERROR: - NOT-COMPLETE\n'
