ffho-site-auto-select 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/lua
  2. local util = require("luci.util")
  3. local json = require("luci.json")
  4. local config = require 'gluon.sites'
  5. local uci = require('luci.model.uci').cursor()
  6. local site = require 'gluon.site_config'
  7. function is_site_valid(site)
  8. for _, tmp in pairs(config) do
  9. if tmp.site_code == site then
  10. return true
  11. end
  12. end
  13. return false
  14. end
  15. function set_currentsite(site)
  16. if site and is_site_valid(site) then
  17. uci:set('currentsite', 'current', 'name', site)
  18. uci:save('currentsite')
  19. uci:commit('currentsite')
  20. return true
  21. end
  22. return false
  23. end
  24. function neighbours(ifname)
  25. local info = util.exec("gluon-neighbour-info -d ff02::2:1001 -p 1001 -r nodeinfo -t 2 -i " .. ifname)
  26. local macs = {}
  27. for _, line in ipairs(util.split(info)) do
  28. local data = json.decode(line)
  29. if data and data["network"] then
  30. local mac = data["network"]["mac"]
  31. if mac then
  32. macs[mac] = data
  33. end
  34. end
  35. end
  36. return macs
  37. end
  38. function get_neighbour_site()
  39. local interfaces = util.split(util.trim(util.exec("batctl if | grep active | grep -v mesh-vpn | cut -d':' -f1")))
  40. for _, ifname in ipairs(interfaces) do
  41. local macs = neighbours(ifname)
  42. for _, node in pairs(macs) do
  43. if node["system"] then
  44. local node_site = node["system"]["site_code"]
  45. if node_site and is_site_valid(node_site) then
  46. return node_site
  47. end
  48. end
  49. end
  50. end
  51. return nil
  52. end
  53. local currentsite = uci:get('currentsite', 'current', 'name')
  54. local configured = is_site_valid(currentsite)
  55. if configured == false then
  56. currentsite = get_neighbour_site()
  57. configured = set_currentsite(currentsite)
  58. end
  59. if configured then
  60. os.execute("rm -f /lib/gluon/cron/ffho-site-auto-select >/dev/null 2>&1")
  61. if site.site_code ~= currentsite then
  62. os.execute("/lib/gluon/site-select/site-upgrade >/dev/null 2>&1")
  63. os.execute("reboot >/dev/null 2>&1")
  64. end
  65. end