003-site-auto-select 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 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. return geo_default_site
  44. end
  45. local currentsite = uci:get('currentsite', 'current', 'name')
  46. local configured = tools.validate_site(currentsite)
  47. if not configured then
  48. local latitude = uci:get_first('gluon-node-info', 'location', 'latitude')
  49. local longitude = uci:get_first('gluon-node-info', 'location', 'longitude')
  50. if latitude and longitude then
  51. currentsite = get_site_by_geo(latitude, longitude)
  52. configured = set_currentsite(currentsite)
  53. end
  54. end
  55. if not configured then
  56. local minute = math.random(0, 59)
  57. local f = io.open('/usr/lib/micron.d/ffho-site-auto-select', 'w')
  58. f:write(string.format('%i * * * * /usr/sbin/ffho-site-auto-select\n', minute))
  59. f:close()
  60. end