#!/usr/bin/env python3
# Copyright 2022 Ubuntu
# See LICENSE file for licensing details.
#
# Learn more at: https://juju.is/docs/sdk

"""Charm the service.

Refer to the following post for a quick-start guide that will help you
develop a new k8s charm using the Operator Framework:

    https://discourse.charmhub.io/t/4208
"""

import logging


from ops.charm import CharmBase
from ops.framework import StoredState
from ops.main import main
from ops.model import ActiveStatus
from charms.osm.sshproxy import SSHProxyCharm

logger = logging.getLogger(__name__)

class SpgwmmeCharm(SSHProxyCharm):
    """Charm the service."""

    _stored = StoredState()

    def __init__(self, *args):
        super().__init__(*args)
        self.state.set_default(ready=False)
        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.hss_relation_changed, self.on_hss_relation_changed)
        self.framework.observe(self.on.nextepcmme_relation_joined, self.on_nextepcmme_relation_joined)

        self.framework.observe(self.on.add_route_action, self._on_add_route)

        self._stored.set_default(things=[])

    def on_config_changed(self, event):
        super().on_config_changed(event)
        self.state.ready = True

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

    def on_start(self, event):
        """Called when the charm is being started"""
        super().on_start(event)
        if not self.verify_credentials():
            event.defer()
            return
        proxy = self.get_ssh_proxy()
        ips, _ = proxy.run("hostname -I")
        ip_list = ips.split(" ")
        self.state.spgwmme_ip = ip_list[3]

    def on_nextepcmme_relation_joined(self, event):
        if self.unit.is_leader():
            if not self.state.ready:
                event.defer()
                return       
            relation = self.model.get_relation("nextepcmme")
            if relation is not None:
               relation.data[self.unit]["spgwmme_ip"] = self.state.spgwmme_ip
               self.model.unit.status = ActiveStatus("Parameter sent from spgwmme:{}". format(self.state.spgwmme_ip))

    def on_hss_relation_changed(self, event):
        if self.model.unit.is_leader():
            stderr = None
            try:
                hss_ip = event.relation.data[event.unit].get("hss_ip")
                if hss_ip is None:
                    return
                proxy = self.get_ssh_proxy()
                cmd1='sudo sed -i "\'s/$hss_ip/{}/g\'" /etc/nextepc/freeDiameter/mme.conf'.format(hss_ip)
                stdout, stderr = proxy.run(cmd1)
                cmd2='sudo sed -i "\'s/$spgw_ip/{}/g\'" /etc/nextepc/freeDiameter/mme.conf'.format(self.state.spgwmme_ip)
                stdout, stderr = proxy.run(cmd2)
                self._restart_spgw()
            except Exception as e:
                event.fail("Action failed {}. Stderr: {}".format(e, stderr))             
        else:
            event.fail("Unit is not leader")

    def _restart_spgw(self):
        cmd = "sudo systemctl restart nextepc-mmed"
        proxy = self.get_ssh_proxy()
        stdout, stderr = proxy.run(cmd)

    def _on_add_route(self, event):
        if self.model.unit.is_leader():
            stderr = None
            try:
                external_prefix = event.params["external-prefix"]
                next_hop = event.params["next-hop"]
                proxy = self.get_ssh_proxy()
                cmd = "sudo route add -net " + external_prefix + " gw " + next_hop
                stdout, stderr = proxy.run(cmd)
            except Exception as e:
                event.fail("Action failed {}. Stderr: {}".format(e, stderr))  
        else:
            event.fail("Unit is not leader")

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