update-settings 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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", int),
  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. elif conversion[1] == int:
  56. orig[origkey] = (conversion[1])(v)
  57. else:
  58. if v.lower() in ("none", "null"):
  59. v = "null"
  60. else:
  61. orig[origkey] = (conversion[1])(v)
  62. i[0] = i[0] + 1
  63. break
  64. if sys.argv[2] == "update":
  65. try:
  66. new = json.loads(sys.stdin.read())
  67. orig = read()
  68. i = [0]
  69. iterate_obj(new, orig, i)
  70. assert i[0] == len(conv), f"Wrong number of entries, {i[0]} != {len(conv)}."
  71. with open(settings, "w+") as json_file:
  72. json.dump(orig, json_file, indent=4)
  73. except Exception as e:
  74. print(e)
  75. sys.exit(1)
  76. sys.exit(0)
  77. if sys.argv[2] == "install":
  78. obj = read()
  79. for k, v in obj.items():
  80. print(f"server.{conv[k][0]}=\"{v}\"")
  81. sys.exit(0)
  82. sys.exit(1)