bootstrap.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import os
  2. import subprocess
  3. from jinja2 import Environment, FileSystemLoader
  4. def sites_default_conf(env, template_vars):
  5. config_name = "sites-default.conf"
  6. template = env.get_template(f"{config_name}.j2")
  7. config = template.render(template_vars)
  8. with open(f"/etc/nginx/includes/{config_name}", "w") as f:
  9. f.write(config)
  10. def nginx_conf(env, template_vars):
  11. config_name = "nginx.conf"
  12. template = env.get_template(f"{config_name}.j2")
  13. config = template.render(template_vars)
  14. with open(f"/etc/nginx/{config_name}", "w") as f:
  15. f.write(config)
  16. def prepare_template_vars():
  17. template_vars = {
  18. 'IPV4_NETWORK': os.getenv("IPV4_NETWORK", "172.22.1"),
  19. 'TRUSTED_NETWORK': os.getenv("TRUSTED_NETWORK", False),
  20. 'SKIP_RSPAMD': os.getenv("SKIP_RSPAMD", "n").lower() in ("y", "yes"),
  21. 'SKIP_SOGO': os.getenv("SKIP_SOGO", "n").lower() in ("y", "yes"),
  22. 'NGINX_USE_PROXY_PROTOCOL': os.getenv("NGINX_USE_PROXY_PROTOCOL", "n").lower() in ("y", "yes"),
  23. 'MAILCOW_HOSTNAME': os.getenv("MAILCOW_HOSTNAME", ""),
  24. 'ADDITIONAL_SERVER_NAMES': os.getenv("ADDITIONAL_SERVER_NAMES", "").replace(',', ' '),
  25. 'HTTP_PORT': os.getenv("HTTP_PORT", "80"),
  26. 'HTTPS_PORT': os.getenv("HTTPS_PORT", "443"),
  27. 'SOGOHOST': os.getenv("SOGOHOST", "sogo-mailcow"),
  28. 'RSPAMDHOST': os.getenv("RSPAMDHOST", "rspamd-mailcow"),
  29. 'PHPFPMHOST': os.getenv("PHPFPMHOST", "php-fpm-mailcow"),
  30. }
  31. ssl_dir = '/etc/ssl/mail/'
  32. template_vars['valid_cert_dirs'] = []
  33. for d in os.listdir(ssl_dir):
  34. full_path = os.path.join(ssl_dir, d)
  35. if not os.path.isdir(full_path):
  36. continue
  37. cert_path = os.path.join(full_path, 'cert.pem')
  38. key_path = os.path.join(full_path, 'key.pem')
  39. domains_path = os.path.join(full_path, 'domains')
  40. if os.path.isfile(cert_path) and os.path.isfile(key_path) and os.path.isfile(domains_path):
  41. with open(domains_path, 'r') as file:
  42. domains = file.read().strip()
  43. domains_list = domains.split()
  44. if domains_list and template_vars["MAILCOW_HOSTNAME"] not in domains_list:
  45. template_vars['valid_cert_dirs'].append({
  46. 'cert_path': full_path + '/',
  47. 'domains': domains
  48. })
  49. return template_vars
  50. def main():
  51. env = Environment(loader=FileSystemLoader('./etc/nginx/conf.d'))
  52. # Render config
  53. print("Render config")
  54. template_vars = prepare_template_vars()
  55. sites_default_conf(env, template_vars)
  56. nginx_conf(env, template_vars)
  57. # Validate config
  58. print("Validate config")
  59. subprocess.run(["nginx", "-qt"])
  60. if __name__ == "__main__":
  61. main()