Skip to content
Snippets Groups Projects
003-site-auto-select 1.98 KiB
Newer Older
#!/usr/bin/lua

local uci = require('luci.model.uci').cursor()
local json = require 'luci.json'
local tools = require 'gluon.site_generate'
local shape = require 'gluon.pointwithinshape'
local site_conf = require 'gluon.site_conf'
function get_config(file)
  local f = io.open(file)
  if f then
    local config = json.decode(f:read('*a'))
    f:close()
    return config
  end
  return nil
end

function set_currentsite(site_code)
  if site_code and tools.validate_site(site_code) then
    uci:set('currentsite', 'current', 'name', site_code)
    uci:save('currentsite')
    return true
  end
  return false
end

function get_site_by_geo(latitude, longitude)
  if not latitude or not longitude then
    return nil
  end
  local sites = tools.get_config('/lib/gluon/site-select/geo.json').features
  for _,site in ipairs(sites) do
    if site.geometry and site.geometry.coordinates then
      local tmp1 = {}
      for _, val in ipairs(site.geometry.coordinates[1]) do
        local tmp2 = {}
        tmp2.x=val[2]
        tmp2.y=val[1]
        table.insert(tmp1, tmp2)
      end
      if shape.PointWithinShape(tmp1, tonumber(latitude), tonumber(longitude)) then
        return site.properties.site_code
      end
  if (site_conf.site_select or {}).geo_default_site then
     return site_conf.site_select.geo_default_site
  end

  return nil
end

local currentsite = uci:get('currentsite', 'current', 'name')
local configured = tools.validate_site(currentsite)
if not configured then
  local latitude = uci:get_first('gluon-node-info', 'location', 'latitude')
  local longitude = uci:get_first('gluon-node-info', 'location', 'longitude')
  if latitude and longitude then
    currentsite = get_site_by_geo(latitude, longitude)
    configured = set_currentsite(currentsite)
  end
end

if not configured then
  local minute = math.random(0, 59)
  local f = io.open('/usr/lib/micron.d/ffho-site-auto-select', 'w')
  f:write(string.format('%i * * * * /usr/sbin/ffho-site-auto-select\n', minute))
  f:close()
end