#!/usr/bin/lua

-- ! LibreMesh
-- ! Copyright (c) 2023  Javier Jorge <jjorge@inti.gob.ar>
-- ! Copyright (c) 2023  Instituto Nacional de Tecnología Industrial
-- ! Copyright (C) 2023  Asociación Civil Altermundi <info@altermundi.net>
-- !
-- ! This program is free software: you can redistribute it and/or modify
-- ! it under the terms of the GNU Affero General Public License as
-- ! published by the Free Software Foundation, either version 3 of the
-- ! License, or (at your option) any later version.
-- !
-- ! This program is distributed in the hope that it will be useful,
-- ! but WITHOUT ANY WARRANTY; without even the implied warranty of
-- ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- ! GNU Affero General Public License for more details.
-- !
-- ! You should have received a copy of the GNU Affero General Public License
-- ! along with this program.  If not, see <http://www.gnu.org/licenses/>.

local JSON = require("luci.jsonc")
local utils = require('lime.utils')
local ubus = require "ubus"

local ifaceip = {}

function get_interface_ip(ifname)
    if ifaceip[ifname] == nil then
        ifaceip[ifname] = string.gsub(utils.unsafe_shell("ip -6 address show "
                .. ifname ..
                " | awk '{if ($1 == \"inet6\") print $2}' | grep fe80 | awk -F/ '{print $1}'"),
            "\n", "")
    end
    return ifaceip[ifname]
end

function get_babel_links_info()
    local conn = ubus.connect()
    local links = {}
    babelneigt_obj = ubus.call(conn, "babeld", "get_neighbours", {})
    if babelneigt_obj ~= nil then
        for key, value in pairs(babelneigt_obj.IPv6) do
            table.insert(links, {
                src_ip = get_interface_ip(value.dev),
                dst_ip = key,
                iface = value.dev
            })
        end
    end
    return links
end

local hostname = io.input("/proc/sys/kernel/hostname"):read("*line")
local result = { [hostname] = get_babel_links_info() }
io.popen("shared-state-async insert babel_links_info", "w"):write(JSON.stringify(result))
