003-site-auto-select 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. function get_config(file)
  7. local f = io.open(file)
  8. if f then
  9. local config = json.decode(f:read('*a'))
  10. f:close()
  11. return config
  12. end
  13. return nil
  14. end
  15. function is_site_valid(site_code)
  16. local sites = get_config('/lib/gluon/site-select/sites.json')
  17. for _, site in pairs(sites) do
  18. if site.site_code == site_code then
  19. return true
  20. end
  21. end
  22. return false
  23. end
  24. function set_currentsite(site_code)
  25. if site_code and is_site_valid(site_code) then
  26. uci:set('currentsite', 'current', 'name', site_code)
  27. uci:save('currentsite')
  28. uci:commit('currentsite')
  29. return true
  30. end
  31. return false
  32. end
  33. function get_site_by_geo(latitude, longitude)
  34. os.execute('gunzip -c /lib/gluon/site-select/site-coords.gz > /tmp/site-coords.json')
  35. local sites = tools.get_config('/tmp/site-coords.json')
  36. os.remove('/tmp/site-coords.json')
  37. for _,site in ipairs(sites) do
  38. if shape.PointWithinShape(site.coords, latitude, longitude) == true then
  39. return site.site_code
  40. end
  41. end
  42. return "ffho_yho"
  43. end
  44. local currentsite = uci:get('currentsite', 'current', 'name')
  45. local configured = is_site_valid(currentsite)
  46. if configured == false then
  47. local latitude = uci:get_first('gluon-node-info', 'location', 'latitude')
  48. local longitude = uci:get_first('gluon-node-info', 'location', 'longitude')
  49. if latitude and longitude then
  50. currentsite = get_site_by_geo(latitude, longitude)
  51. configured = set_currentsite(currentsite)
  52. end
  53. end
  54. if configured == false then
  55. local minute = math.random(0, 59)
  56. local f = io.open('/usr/lib/micron.d/ffho-site-auto-select', 'w')
  57. f:write(string.format('%i * * * * /usr/sbin/ffho-site-auto-select\n', minute))
  58. f:close()
  59. end