#!/usr/bin/env python3
# Copyright 2022 preethika.p
# 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 HssCharm(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.nextepchss_relation_joined, self.on_nextepchss_relation_joined)
        self.framework.observe(self.on.mme_relation_changed, self.on_mme_relation_changed)
        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.hss_ip = ip_list[1]


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

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

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

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