#!/usr/bin/env python3
"""
Return (first or fastest) ip4 address for interface or the list of available interfaces.

Usage:
    felix-get-ip [options] [<interface_name>]

Options:
    --fastest                   Return ip for fastest network
    -v, --verbose               Verbose output

Arguments:
    <interface_name>            Name of the ethernet interface, see ifconfig
"""
import functools
import netifaces
import os
import sys

print = functools.partial(print, flush=True)

# add the ../python path to find felix python libs
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'python'))

from docopt import docopt  # noqa: E402

from felixtag import FELIX_TAG


def get_first_ip(interface):
    """TBD"""
    address = netifaces.ifaddresses(interface)
    if address and address[netifaces.AF_INET] and address[netifaces.AF_INET][0] and address[netifaces.AF_INET][0]['addr']:
        return address[netifaces.AF_INET][0]['addr']
    return None


if __name__ == "__main__":
    """felix-get-ip."""

    args = docopt(__doc__, version=sys.argv[0] + " " + FELIX_TAG)

    verbose = args['--verbose']
    interface = args['<interface_name>']
    fastest = args['--fastest']

    ifaces = netifaces.interfaces()

    if interface:
        if interface not in ifaces:
            print("ERROR - interface does not exist", interface)
            exit(1)

        ip = get_first_ip(interface)
        if ip:
            print(ip, end='')
            exit(0)

        exit(1)

    elif fastest:
        fastest = None
        speed = 0
        for iface in ifaces:
            try:
                with open('/sys/class/net/' + iface + '/speed', 'r') as content_file:
                    content = content_file.read().strip()

                if int(content) > speed:
                    speed = int(content)
                    fastest = iface

            except IOError:
                pass

        if fastest:
            # print(fastest, speed)
            ip = get_first_ip(fastest)
            if ip:
                print(ip, end='')
                exit(0)

            exit(1)

        exit(1)

    else:
        # list all interfaces
        print(ifaces, end='')
        exit(0)
