003-site-auto-select 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/lua
  2. local uci = require('luci.model.uci').cursor()
  3. local json = require 'luci.json'
  4. local tools = require 'gluon.site_generate'
  5. local shape = require 'gluon.pointwithinshape'
  6. local geo_default_site = "ffho_yho"
  7. function get_config(file)
  8. local f = io.open(file)
  9. if f then
  10. local config = json.decode(f:read('*a'))
  11. f:close()
  12. return config
  13. end
  14. return nil
  15. end
  16. function is_site_valid(site_code)
  17. local sites = get_config('/lib/gluon/site-select/sites.json')
  18. for _, site in pairs(sites) do
  19. if site.site_code == site_code then
  20. return true
  21. end
  22. end
  23. return false
  24. end
  25. function set_currentsite(site_code)
  26. if site_code and is_site_valid(site_code) then
  27. uci:set('currentsite', 'current', 'name', site_code)
  28. uci:save('currentsite')
  29. uci:commit('currentsite')
  30. return true
  31. end
  32. return false
  33. end
  34. function get_site_by_geo(latitude, longitude)
  35. if not latitude or not longitude then
  36. return nil
  37. end
  38. local sites = tools.get_config('/lib/gluon/site-select/geo.json').features
  39. for _,site in ipairs(sites) do
  40. if site.geometry and site.geometry.coordinates and shape.PointWithinShape(site.geometry.coordinates, latitude, longitude) then
  41. return site.properties.site_code
  42. end
  43. end
  44. return geo_default_site
  45. end
  46. local currentsite = uci:get('currentsite', 'current', 'name')
  47. local configured = is_site_valid(currentsite)
  48. if configured == false then
  49. local latitude = uci:get_first('gluon-node-info', 'location', 'latitude')
  50. local longitude = uci:get_first('gluon-node-info', 'location', 'longitude')
  51. if latitude and longitude then
  52. currentsite = get_site_by_geo(latitude, longitude)
  53. configured = set_currentsite(currentsite)
  54. end
  55. end
  56. if configured == false then
  57. local minute = math.random(0, 59)
  58. local f = io.open('/usr/lib/micron.d/ffho-site-auto-select', 'w')
  59. f:write(string.format('%i * * * * /usr/sbin/ffho-site-auto-select\n', minute))
  60. f:close()
  61. end