from leapp.actors import Actor
from leapp.models import NetworkManagerConfig
from leapp.tags import ApplicationsPhaseTag, IPUWorkflowTag

snippet_path = '/usr/lib/NetworkManager/conf.d/10-dhcp-dhclient.conf'
snippet_data = ("# Generated by leapp when upgrading from RHEL7 to RHEL8\n"
                "[main]\n"
                "dhcp=dhclient\n")


class NetworkManagerUpdateConfig(Actor):
    """
    Updates NetworkManager configuration for Red Hat Enterprise Linux 8.

    On Red Hat Enterprise Linux 7 NetworkManager uses the "dhclient" DHCP backend by default, while
    the default is "internal" on Red Hat Enterprise Linux 8. We want to keep "dhclient" enabled on
    upgrade, unless the user explicitly chose another backend in the configuration. To do so, we
    drop a configuration snippet in /usr/lib.
    """

    name = 'network_manager_update_config'
    consumes = (NetworkManagerConfig,)
    produces = ()
    tags = (ApplicationsPhaseTag, IPUWorkflowTag)

    def process(self):
        for nm_config in self.consume(NetworkManagerConfig):
            self.log.info('Consuming dhcp={}'.format(nm_config.dhcp))
            if nm_config.dhcp == '':
                try:
                    with open(snippet_path, 'w') as f:
                        f.write(snippet_data)
                        self.log.info('Written the following to {}:\n{}\n'.format(snippet_path, snippet_data))
                except IOError as e:
                    self.log.warning('Write error: {}'.format(e))
            break
