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

# Copyright 2015 Spotify AB. All rights reserved.
#
# The contents of this file are 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 ast
import logging

logger = logging.getLogger('eos_install_config')

DOCUMENTATION = '''
---
module: napalm_install_config
author: David Barroso <dbarroso@spotify.net>
version_added: "1.0.0"
short_description: Replaces the configuration taken from a file on a device supported by NAPALM.
description:
    This library will take the configuration from a file and load it into a device running any OS supported by napalm.
    The old configuration will be replaced by the new one.

requirements:
    - napalm

options:
    hostname:
        description: IP or FQDN of the device you want to connect to
        required: true
    username:
        description: Username
        required: true
    dev_os:
        description: OS running the device
        required: true
    password:
        description: Password
        required: true
    timeout:
        description: Timeout for connections and requests to device
        required: false
        default: 60
    config_file:
        description: Where to load the configuration from.
        required: true
    commit_changes:
        description: If set to True the configuration will be actually replaced. If the set to False, we will not
                     apply the changes, just check the differences.
        required: true
    replace_config:
        description: If set to True the entire configuration on the device will be replaced during the commit. If
                     set to False, we will merge the new config with the existing one. Default: False.
        required: False
    diff_file:
        description: A file where to store the "diff" between the running configuration and the new configuration. If
                     it's not set the diff between configurations is not saved.
        required: False
    get_diffs:
        description:
            - Set to false to not have any diffs generated and always apply config.  Useful if platform does
              not support commands being used to generated diffs.  Note: By default diffs are generated
              even if the diff_file param is not set.
        choices: ['true', 'false']
        required: False
'''

EXAMPLES = '''
    In our playbook would have something like:

  tasks:
  - name: Assemble configuration
    assemble: src=../compiled/{{ inventory_hostname }}/ dest=../compiled/{{ inventory_hostname }}/running.conf
  - name: Push Configuration
    napalm_install_config:
        hostname={{ inventory_hostname }}
        username=dbarroso
        dev_os={{os}}
        password=p4ssw0rd
        config_file=../compiled/{{ inventory_hostname }}/running.conf
        commit_changes={{ commit_changes }}
        replace_config={{ replace_config }}
        diff_file=../compiled/{{ inventory_hostname }}/diff
        timeout={{timeout}}

    From the CLI we would trigger the playbook like:

        # We don't commit changes, we only want to check the diff
        $ ansible-playbook -v -e commit_changes=0 napalm_test.yml

        or

        # We actually commit the changes
        $ ansible-playbook -v -e commit_changes=1 napalm_test.yml
'''


def save_to_file(content, filename):
    with open(filename, 'w') as f:
        f.write(content)


def main():
    module = AnsibleModule(
        argument_spec=dict(
            hostname=dict(required=True),
            username=dict(required=True),
            password=dict(required=True),
            timeout=dict(required=False, default=60, type='int'),
            config_file=dict(required=True),
            dev_os=dict(required=True),
            commit_changes=dict(required=True),
            replace_config=dict(required=True),
            diff_file=dict(required=False, default=None),
            get_diffs=dict(required=False, choices=BOOLEANS, type='bool', default=True)
        ),
        supports_check_mode=True
    )

    hostname = module.params['hostname']
    username = module.params['username']
    dev_os = module.params['dev_os']
    password = module.params['password']
    timeout = module.params['timeout']

    config_file = module.params['config_file']
    commit_changes = module.params['commit_changes']
    replace_config = module.params['replace_config']
    diff_file = module.params['diff_file']
    get_diffs = module.params['get_diffs']

    if commit_changes.__class__ is str:
        commit_changes = ast.literal_eval(commit_changes)
    if replace_config.__class__ is str:
        replace_config = ast.literal_eval(replace_config)

    network_driver = get_network_driver(dev_os)

    device = network_driver(hostname, username, password, timeout)
    device.open()

    if replace_config:
        device.load_replace_candidate(filename=config_file)
    else:
        device.load_merge_candidate(filename=config_file)

    if get_diffs:
        diff = device.compare_config().encode('utf-8')
        changed = len(diff) > 0
    else:
        changed = True
        diff = None

    if diff_file is not None and get_diffs:
        save_to_file(diff, diff_file)

    if module.check_mode or not commit_changes:
        device.discard_config()
        module.exit_json(changed=changed, msg=diff)
    else:
        if changed:
            device.commit_config()
        module.exit_json(changed=changed, msg=diff)

    logger.info('DEVICE=%s CHANGED=%s STATUS=%s' % (hostname, changed, 'OK'))

    device.close()

from ansible.module_utils.basic import *
from napalm import get_network_driver

main()
