#!/usr/bin/env python3


from sys import exit
from json import loads
from os.path import isfile

from pyeole.service import unmanaged_service


VERIFY_NETWORK_FILE = '/etc/eole/network.json'


def _is_valid_ip_eth0(is_dhcp, nom_carte, timeout=60):
    idx = 0
    while True:
        eths = get_devices()
        real_ip_eth0 = eths.get(nom_carte, ('169.254.0.1'))[0]
        if is_dhcp:
            if real_ip_eth0 != "169.254.0.1":
                return True
        else:
            if real_ip_eth0 == ip_eth0:
                return True
        if idx == timeout:
            return False
        time.sleep(1)
        idx += 1


def is_valid_ip_eth0():
    # Apply network configuration to ensure new interfaces to be up
    # Some kernel params are set on interfaces #29610
    if not isfile(VERIFY_NETWORK_FILE):
        return
    with open(VERIFY_NETWORK_FILE, 'r') as fh:
        network = loads(fh)
    cache()
    is_dhcp = network['eth0_method'] == 'dhcp'
    if is_dhcp:
        nom_carte = None
    else:
        nom_carte = network['nom_zone_eth0']
    if _is_valid_ip_eth0(is_dhcp, nom_carte):
        return
    idx = 0
    while True:
        unmanaged_service('restart', 'systemd-networkd', 'systemd', display='console')
        if _is_valid_ip_eth0(is_dhcp, nom_carte, timeout=30):
            return
        idx += 1
        if idx == 2:
            break
    print('Unable to obtain IP address')
    exit(1)


def main():
    is_valid_ip_eth0()


if __name__ == '__main__':
    main()
