#!/usr/bin/lua
--! Copyright (C) 2021 Santiago Piccinini <spiccinini@altermundi.net>
--!
--! This is free software, licensed under the GNU Affero General Public License v3.

local ubus = require "ubus"
local utils = require "lime.utils"

local conn = ubus.connect()
if not conn then
    error("Failed to connect to ubus")
end

local wan4_status = conn:call("network.interface.wan", "status", {})
local wan_ifc = wan4_status.device

--! change the default route from the nonworking metric value to the working metric value
local nonworking_route = utils.unsafe_shell("ip route show default metric 84831 | grep " .. wan_ifc):gsub("\n","")
if nonworking_route ~= '' then
    os.execute("ip r add " .. nonworking_route .. " metric 0")
    os.execute("ip r del " .. nonworking_route .. " metric 84831")
end

--! install a route with proto value 7 that will be redistributed by babeld
for _, route4 in ipairs(wan4_status.route) do
    if route4.target == "0.0.0.0" and route4.mask == 0 then
        local r = ("ip r add default via " .. route4.nexthop .. " dev " .. wan4_status.device .. " proto 7 metric 10")
        os.execute(r)
    end
end
