#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# Example output from agent:
# <<<ip_a_r>>>
# default via 10.10.0.1 dev wlan0  proto static
# 10.10.0.0/16 dev wlan0  proto kernel  scope link  src 10.10.0.41  metric 9


def parse_lnx_ip_route(line):
    def parse_network(n):
        if n == "default":
            return "0.0.0.0/0"
        return n

    route = {
        "target": parse_network(line[0]),
    }

    line = line[1:]
    while line:
        if line[0] == "dev":
            route.setdefault("type", "local")
            route["device"] = line[1]
            line = line[2:]
        elif line[0] == "via":
            route["type"] = "gateway"
            route["gateway"] = line[1]
            line = line[2:]
        else:
            line = line[1:]

    return route


def inv_lnx_ip_r(info):
    routes = inv_tree_list("networking.routes:")
    for line in info:
        routes.append(parse_lnx_ip_route(line))


inv_info['lnx_ip_r'] = {
    "inv_function": inv_lnx_ip_r,
}
