update-settings 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/usr/bin/env python3
  2. import json, sys, subprocess, ast
  3. if len(sys.argv) < 3:
  4. print(f"Error, use {sys.argv[0]} install|update")
  5. sys.exit(1)
  6. settings = sys.argv[1]
  7. conv = {
  8. "LISTENIP": ("listen.ip", str),
  9. "PORT": ("listen.port", int),
  10. "GIT": ("git", bool),
  11. "BASEPATH": ("basepath.dir", str),
  12. "ENFORCE_BASEPATH": ("basepath.enforce", bool),
  13. "SSL_CERTIFICATE": ("ssl.certificate", str),
  14. "SSL_KEY": ("ssl.key", str),
  15. "IGNORE_SSL": ("ssl.ignore", bool),
  16. "HASS_API": ("hass.api.url", str),
  17. "HASS_WS_API": ("hass.api.ws-url", str),
  18. "HASS_API_PASSWORD": ("hass.api.password", str),
  19. "USERNAME": ("login.username", str),
  20. "PASSWORD": ("login.password", str),
  21. "ALLOWED_NETWORKS": ("allowed.networks", list),
  22. "ALLOWED_DOMAINS": ("allowed.domains", list),
  23. "BANNED_IPS": ("ban.ips", list),
  24. "BANLIMIT": ("ban.limit", list),
  25. "IGNORE_PATTERN": ("ignore-pattern", list),
  26. "DIRSFIRST": ("dirs-first", bool),
  27. "SESAME": ("sesame.key", str),
  28. "SESAME_TOTP_SECRET": ("sesame.secret", str),
  29. "VERIFY_HOSTNAME": ("verify-hostname", bool),
  30. "ENV_PREFIX": ("env-prefix", str),
  31. "NOTIFY_SERVICE": ("notify-service", str)
  32. }
  33. def read(param=None):
  34. with open(settings, "r") as json_file:
  35. obj = json.load(json_file)
  36. if param is None:
  37. return obj
  38. if param in obj:
  39. return obj[param]
  40. sys.exit(1)
  41. def iterate_obj(obj, orig, i, path=""):
  42. if not isinstance(obj, dict):
  43. raise Exception("Invalid data")
  44. for k,v in obj.items():
  45. if isinstance(v, dict):
  46. iterate_obj(v, orig, i, path+k+".")
  47. else:
  48. key=path+k
  49. for origkey, conversion in conv.items():
  50. if key == conversion[0]:
  51. if conversion[1] == list:
  52. orig[origkey] = ast.literal_eval(v)
  53. elif conversion[1] == bool:
  54. orig[origkey] = True if v.lower() == "true" else False
  55. else:
  56. if v.lower() in ("none", "null"):
  57. v = "null"
  58. else:
  59. orig[origkey] = (conversion[1])(v)
  60. i[0] = i[0] + 1
  61. break
  62. if sys.argv[2] == "update":
  63. try:
  64. new = json.loads(sys.stdin.read())
  65. orig = read()
  66. i = [0]
  67. iterate_obj(new, orig, i)
  68. assert i[0] == len(conv), f"Wrong number of entries, {i[0]} != {len(conv)}."
  69. with open(settings, "w+") as json_file:
  70. json.dump(orig, json_file, indent=4)
  71. except Exception as e:
  72. print(e)
  73. sys.exit(1)
  74. sys.exit(0)
  75. if sys.argv[2] == "install":
  76. obj = read()
  77. for k, v in obj.items():
  78. print(f"server.{conv[k][0]}=\"{v}\"")
  79. sys.exit(0)
  80. sys.exit(1)