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

  Copyright 2017 Marcos Gutierrez <gmarcos@altermindi.net>
  Copyright 2017 Nicolas Echaniz <nicoechaniz@altermundi.net>
]]--

local ubus = require "ubus"
local utils = require('lime.utils')
local metrics = require 'lime-metrics'
local json = require 'luci.jsonc'


local conn = ubus.connect()

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

local function get_metrics(msg)
    local result = metrics.get_metrics(msg.target)
    utils.printJson(result)
end

local function get_loss(msg)
    local result = metrics.get_loss(msg.target)
    utils.printJson(result)
end

local function get_gateway(msg)
    utils.printJson(metrics.get_gateway())
end

local function get_path(msg)
    utils.printJson(metrics.get_last_internet_path())
end

local function get_internet_status(msg)
    utils.printJson(metrics.get_internet_status())
end

local function get_station_traffic(msg)
    utils.printJson(metrics.get_station_traffic(msg))
end

local methods = {
	get_metrics = { target = 'value' },
	get_loss = { target = 'value' },
    get_gateway = { no_params = 0 },
    get_path = { target = 'value' },
    get_last_internet_path = { no_params = 0 },
    get_internet_status = { no_params = 0 },
    get_station_traffic = { iface = 'value', station_mac = 'value' }
}

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

if arg[1] == 'call' then
    local msg = io.read()
    msg = json.parse(msg)
    if       arg[2] == 'get_metrics'            then get_metrics(msg)
    elseif   arg[2] == 'get_loss'               then get_loss(msg)
    elseif   arg[2] == 'get_gateway'            then get_gateway(msg)
    elseif   arg[2] == 'get_path'               then get_path(msg)
    elseif   arg[2] == 'get_last_internet_path' then get_path(msg)
    elseif   arg[2] == 'get_internet_status'    then get_internet_status(msg)
    elseif   arg[2] == 'get_station_traffic'    then get_station_traffic(msg)
    else                                        utils.printJson({ error = "Method not found" })
    end
end