003-site-auto-select 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 site_conf = require 'gluon.site_conf'
  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 set_currentsite(site_code)
  17. if site_code and tools.validate_site(site_code) then
  18. uci:set('currentsite', 'current', 'name', site_code)
  19. uci:save('currentsite')
  20. return true
  21. end
  22. return false
  23. end
  24. function get_site_by_geo(latitude, longitude)
  25. if not latitude or not longitude then
  26. return nil
  27. end
  28. local sites = tools.get_config('/lib/gluon/site-select/geo.json').features
  29. for _,site in ipairs(sites) do
  30. if site.geometry and site.geometry.coordinates then
  31. local tmp1 = {}
  32. for _, val in ipairs(site.geometry.coordinates[1]) do
  33. local tmp2 = {}
  34. tmp2.x=val[2]
  35. tmp2.y=val[1]
  36. table.insert(tmp1, tmp2)
  37. end
  38. if shape.PointWithinShape(tmp1, tonumber(latitude), tonumber(longitude)) then
  39. return site.properties.site_code
  40. end
  41. end
  42. end
  43. if (site_conf.site_select or {}).geo_default_site then
  44. return site_conf.site_select.geo_default_site
  45. end
  46. return nil
  47. end
  48. local currentsite = uci:get('currentsite', 'current', 'name')
  49. local configured = tools.validate_site(currentsite)
  50. if not configured then
  51. local latitude = uci:get_first('gluon-node-info', 'location', 'latitude')
  52. local longitude = uci:get_first('gluon-node-info', 'location', 'longitude')
  53. if latitude and longitude then
  54. currentsite = get_site_by_geo(latitude, longitude)
  55. configured = set_currentsite(currentsite)
  56. end
  57. end
  58. if not configured then
  59. local minute = math.random(0, 59)
  60. local f = io.open('/usr/lib/micron.d/ffho-site-auto-select', 'w')
  61. f:write(string.format('%i * * * * /usr/sbin/ffho-site-auto-select\n', minute))
  62. f:close()
  63. end