#!/bin/env python

import time
import paramiko
from config import *

default_args = [
    ('--username', 'admin'),
    ('--password', 'contrail123'),
    ('--region', 'RegionOne'),
    ('--tenant', 'admin'),
    ('--api-server', '127.0.0.1')]

class Vsrx():
    def __init__(self):
        self.argv_orig = sys.argv
        self.mgmt_addr = None

    def argv_set(self, cmd):
        args = cmd.split()
        sys.argv = self.argv_orig + args
        for arg in default_args:
            if not arg[0] in sys.argv:
                sys.argv.insert(1, arg[0])
                sys.argv.insert(2, arg[1])

    def service_launch(self):
        print 'Launch service instance.'
        cmd = 'add service-instance vsrx-nat --template vsrx-nat ' + \
                '--management-network admin:management ' + \
                '--left-network access ' + \
                '--left-route 0.0.0.0/0 ' + \
                '--right-network admin:public'

        self.argv_set(cmd)
        config = ConfigShell()
        args = config.parse()
        config.clients(args)
        config.execute(args)

        print 'Waiting ...'
        timeout = 12
        while timeout:
            time.sleep(3)
            vm = config.nova.servers.find(name = 'vsrx-nat_1')
            if vm.status != 'BUILD':
                print 'VM %s is %s' %(vm.name, vm.status)
                break
            timeout -= 1
        self.mgmt_addr = vm.addresses['management'][0]['addr']

        print 'Post-launch configuration.'
        cmd_list = [
            'delete vm-interface vsrx-nat_1:management --security-group default',
            'delete vm-interface vsrx-nat_1:access --security-group default',
            'delete vm-interface vsrx-nat_1:public --security-group default']
        for cmd in cmd_list:
            self.argv_set(cmd)
            config = ConfigShell()
            args = config.parse()
            config.clients(args)
            config.execute(args)

    def service_boot(self):
        print 'Waiting for Junos boots up...'
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        while True:
            try:
                ssh.connect(self.mgmt_addr, username = 'root',
                        password = 'passWD')
                break
            except:
                continue
        ssh.close()

    def service_netconf_enable(self):
        print 'Enable NETCONF service.'

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self.mgmt_addr, username = 'root', password = 'passWD')
        ssh.exec_command('cli -c "configure;set system services netconf ssh;set security zones security-zone trust interfaces ge-0/0/0.0 host-inbound-traffic system-services all;commit"')
        time.sleep(10)
        ssh.close()

    def service_provisioning(self):
        print 'Provisioning service.'

        from ncclient import manager as netconf

        nc_client = netconf.connect(host = self.mgmt_addr, port = 830,
                username = 'root', password = 'passWD', hostkey_verify = False,
                device_params={'name':'junos'})

        list = []
        conf = open('vsrx-nat.conf', 'r')
        for line in conf:
            line.rstrip('\n')
            list.append(line)
        conf.close()
        nc_client.load_configuration(action = 'set', config = list)
        nc_client.commit()
        nc_client.close_session()


if __name__ == '__main__':
    vsrx = Vsrx()
    vsrx.service_launch()
    vsrx.service_boot()
    vsrx.service_netconf_enable()
    vsrx.service_provisioning()

