bootstrap.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. ipv4_network = os.getenv("IPV4_NETWORK", "172.22.1")
  18. template_vars = {
  19. 'IPV4_NETWORK': ipv4_network,
  20. 'TRUSTED_NETWORK': os.getenv("TRUSTED_NETWORK", False),
  21. 'SKIP_RSPAMD': os.getenv("SKIP_RSPAMD", "n").lower() in ("y", "yes"),
  22. 'SKIP_SOGO': os.getenv("SKIP_SOGO", "n").lower() in ("y", "yes"),
  23. 'NGINX_USE_PROXY_PROTOCOL': os.getenv("NGINX_USE_PROXY_PROTOCOL", "n").lower() in ("y", "yes"),
  24. 'MAILCOW_HOSTNAME': os.getenv("MAILCOW_HOSTNAME", ""),
  25. 'ADDITIONAL_SERVER_NAMES': os.getenv("ADDITIONAL_SERVER_NAMES", "").replace(',', ' '),
  26. 'HTTP_PORT': os.getenv("HTTP_PORT", "80"),
  27. 'HTTPS_PORT': os.getenv("HTTPS_PORT", "443"),
  28. 'SOGOHOST': os.getenv("SOGOHOST", ipv4_network + ".248"),
  29. 'RSPAMDHOST': os.getenv("RSPAMDHOST", "rspamd-mailcow"),
  30. 'PHPFPMHOST': os.getenv("PHPFPMHOST", "php-fpm-mailcow"),
  31. }
  32. ssl_dir = '/etc/ssl/mail/'
  33. template_vars['valid_cert_dirs'] = []
  34. for d in os.listdir(ssl_dir):
  35. full_path = os.path.join(ssl_dir, d)
  36. if not os.path.isdir(full_path):
  37. continue
  38. cert_path = os.path.join(full_path, 'cert.pem')
  39. key_path = os.path.join(full_path, 'key.pem')
  40. domains_path = os.path.join(full_path, 'domains')
  41. if os.path.isfile(cert_path) and os.path.isfile(key_path) and os.path.isfile(domains_path):
  42. with open(domains_path, 'r') as file:
  43. domains = file.read().strip()
  44. domains_list = domains.split()
  45. if domains_list and template_vars["MAILCOW_HOSTNAME"] not in domains_list:
  46. template_vars['valid_cert_dirs'].append({
  47. 'cert_path': full_path + '/',
  48. 'domains': domains
  49. })
  50. return template_vars
  51. def main():
  52. env = Environment(loader=FileSystemLoader('./etc/nginx/conf.d'))
  53. # Render config
  54. print("Render config")
  55. template_vars = prepare_template_vars()
  56. sites_default_conf(env, template_vars)
  57. nginx_conf(env, template_vars)
  58. # Validate config
  59. print("Validate config")
  60. subprocess.run(["nginx", "-qt"])
  61. if __name__ == "__main__":
  62. main()