"""
    osconfig module:
        This module is in charge of changing configuration files for
        pdfcd on the host OS. This relates to things like network, dhcp,
        wifi, firewall changes. Pdfcd should be able to make simple abstracted
        calls into this module so that if we need to change what type of OS config
        we need to support only this module would change.
"""

from paradrop.lib.utils import datastruct
from .uciutils import restoreConfigFile


WAIT_ONLINE_FILE = "/etc/systemd/system/systemd-networkd-wait-online.service"
WAIT_ONLINE_TEMPLATE = """
# This file was automatically generated by paradrop-daemon.

[Unit]
Description=Wait for Network to be Configured
Documentation=man:systemd-networkd-wait-online.service(8)
DefaultDependencies=no
Conflicts=shutdown.target
Requisite=systemd-networkd.service
After=systemd-networkd.service
Before=network-online.target

[Service]
Type=oneshot
ExecStart=/lib/systemd/systemd-networkd-wait-online --interface {interface}
RemainAfterExit=yes

[Install]
WantedBy=network-online.target
"""


def applyWaitOnlineFix(update):
    """
    Configure systemd-networkd to wait for WAN interface only.

    This fixes the long delay on system startup while it waits for all network
    interfaces to be connected.
    """
    hostConfig = update.cache_get('hostConfig')
    ifname = datastruct.getValue(hostConfig, 'wan.interface', None)

    if ifname is not None:
        with open(WAIT_ONLINE_FILE, "w") as output:
            output.write(WAIT_ONLINE_TEMPLATE.format(interface=ifname))


def revertConfig(update, theType):
    """
    Tell the UCI module to revert changes to the old state of the chute.
    """
    restoreConfigFile(update.new, theType)
