#!/usr/bin/env lua
--[[
Copyright 2017 Marcos Gutierrez <gmarcos87@gmail.com>
Copyright 2020 Santiago Piccinini <spiccinini@altermundi.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-3.0
]]--


local ubus = require "ubus"
local iwinfo = require "iwinfo"
local json = require "luci.jsonc"
local config = require("lime.config")
local wireless = require "lime.wireless"
local network = require 'lime.network'
local utils = require 'lime.utils'
local location = require 'lime.location'


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

local function _get_location(msg)
    local result = {location = {}, default = false}

    local coords = location.get_node()
    if not coords then
        result.default = true
        coords = location.get_community() or {lat="FIXME", long="FIXME"}
    end

    result.location.lat = coords.lat
    result.location.lon = coords.long
    result.status = "ok"
    return result
end

local function get_location(msg)
  utils.printJson(_get_location(msg))
end

local function set_location(msg)
    location.set(msg.lat, msg.lon)
    utils.printJson({ lat = msg.lat, lon = msg.lon, status = 'ok' });
end

local function nodes_and_links()
  local hostname = utils.hostname()
  local result = {}
  result[hostname] = location.nodes_and_links()
  utils.printJson(result)
end

function all_nodes_and_links(msg)
  print('{"result":'..utils.unsafe_shell("shared-state get nodes_and_links")..'}')
end

local methods = {
    all_nodes_and_links = { no_params = 0},
    nodes_and_links = { no_params = 0},
    get = { no_params = 0 },
    set = { lat = 'value', lon = 'value' }
}

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] == 'get'	        then get_location(msg)
	elseif   arg[2] == 'set'	        then set_location(msg)
	elseif   arg[2] == 'nodes_and_links'	        then nodes_and_links(msg)
	elseif   arg[2] == 'all_nodes_and_links'	        then all_nodes_and_links(msg)
    else utils.printJson({ error = "Method not found" })
    end
end
