#!/usr/bin/env lua
--[[
  Copyright (C) 2021 LibreMesh.org
  This is free software, licensed under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3

  Copyright 2021 Santiago Piccinini <spiccinini@altermindi.net>
]]--

local ubus = require "ubus"
local json = require "luci.jsonc"
local utils = require "lime.utils"

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

local function is_connected()
	local exit_status = os.execute('check-internet')
	local connected = false
	if exit_status == 0 then
		connected = true
	end
	return utils.printJson({status = 'ok', connected = connected})
end

local methods = {
	is_connected = { no_params = 0 }
}

if arg[1] == 'list' then
	utils.printJson(methods)
end

if arg[1] == 'call' then
	local msg = utils.rpcd_readline()
	msg = json.parse(msg)
	if	  arg[2] == 'is_connected' then is_connected(msg)
	else utils.printJson({ error = "Method not found" })
	end
end
