#!/usr/bin/env python3
# Copyright 2020 Canonical Ltd.
#
# 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 subprocess
import sys
import traceback

from charms.osm import libansible
from charms.osm.sshproxy import SSHProxyCharm
from ops.charm import CharmBase, CharmEvents
from ops.framework import StoredState, EventBase, EventSource
from ops.main import main
from ops.model import (
    ActiveStatus,
    BlockedStatus,
    MaintenanceStatus,
    WaitingStatus,
    ModelError,
)


sys.path.append("lib")


class VyosCharm(SSHProxyCharm):
    def __init__(self, framework, key):
        super().__init__(framework, key)

        # Register all of the events we want to observe
        self.framework.observe(self.on.config_changed, self.on_config_changed)
        self.framework.observe(self.on.install, self.on_install)
        self.framework.observe(self.on.start, self.on_start)
        self.framework.observe(self.on.upgrade_charm, self.on_upgrade_charm)
        # Charm actions (primitives)
        self.framework.observe(
            self.on.add_port_forward_action, self.on_add_port_forward_action
        )
        self.framework.observe(
            self.on.remove_port_forward_action, self.on_remove_port_forward_action
        )

    def on_config_changed(self, event):
        """Handle changes in configuration"""
        super().on_config_changed(event)

    def on_install(self, event):
        """Called when the charm is being installed"""
        super().on_install(event)
        self.unit.status = MaintenanceStatus("Installing Ansible")
        libansible.install_ansible_support()
        self.unit.status = ActiveStatus()

    def on_start(self, event):
        """Called when the charm is being started"""
        super().on_start(event)

    def on_add_port_forward_action(self, event):
        """Adds a port forward rule."""
        self._run_playbook(
            event,
            "add-port-forward.yaml",
            {
                "sourcePort": event.params["sourcePort"],
                "destinationPort": event.params["destinationPort"],
                "destinationAddress": event.params["destinationAddress"],
                "ruleNumber": event.params["ruleNumber"],
            })

    def on_remove_port_forward_action(self, event):
        """Remove a port forward rule."""
        self._run_playbook(
            event,
            "remove-port-forward.yaml",
            {
                "ruleNumber": event.params["ruleNumber"],
            })

    def on_upgrade_charm(self, event):
        """Upgrade the charm."""

    def _run_playbook(self, event, playbook, variables):
        try:
            config = self.model.config
            result = libansible.execute_playbook(
                playbook,
                config["ssh-hostname"],
                config["ssh-username"],
                config["ssh-password"],
                variables,
            )
            event.set_results({"output": result})
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            err = traceback.format_exception(exc_type, exc_value, exc_traceback)
            event.fail(message="Playbook " + playbook + " failed: " + str(err))


if __name__ == "__main__":
    main(VyosCharm)
