003-site-auto-select 1.9 KB

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