#!/usr/bin/env python3

import logging
from ipaddress import ip_address
from json import loads
from subprocess import check_output

from requests import get


UPDATE_URL = '${url}'
USERNAME = '${username}'
PASSWORD = '${password}'

# <%text>
logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger('DynDNS')
try:
    ips = set()

    iproute = loads(check_output(['ip', '-json', 'address', 'show', 'scope', 'global']))

    for iface in iproute:
        if not iface['ifname'].startswith('ppp'):
            LOG.debug(f'ignoring {iface["ifname"]}')
            continue

        LOG.info(f'working on {iface["ifname"]}')
        for ip in iface['addr_info']:
            try:
                addr = ip_address(ip['local'])

                LOG.info(f'{iface["ifname"]} has ip {addr.compressed}')
                ips.add(addr.compressed)
            except Exception:
                continue

        if ips:
            LOG.info('got some addresses!')
            break

    url = UPDATE_URL.format(
        ips=','.join(sorted(ips))
    )

    LOG.info(url)

    r = get(
        url,
        auth=(
            USERNAME,
            PASSWORD,
        ),
    )
    r.raise_for_status()
except Exception as e:
    logging.exception(e)

# </%text>
