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

  Copyright 2020 German Ferrero <germanferrero@altermundi.net>
]]--

local ubus = require "ubus"
local json = require 'luci.jsonc'
local utils = require 'lime.utils'
local bat_hosts = require 'bat-hosts'

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

local function get_bathost(msg)
    if not msg.mac or not utils.is_valid_mac(msg.mac) then
      utils.printJson({ status = "error", message = "invalid mac" })
      return
    end

    if msg.outgoing_iface and not utils.has_value(utils.get_ifnames(), msg.outgoing_iface) then
      utils.printJson({ status = "error", message = "invalid outgoing interface" })
      return
    end
    local bathost = bat_hosts.get_bathost(msg.mac, msg.outgoing_iface)
    local result = {}
    if bathost.hostname ~= nil then
      result.status = "ok"
      result.bathost = bathost
    else
      result.status = "error"
      result.error = "Couldn't retrieve hostname"
    end
    utils.printJson(result)
end

local methods = {
    get_bathost = { mac = 'value', outgoing_iface = 'value'}
}

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

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