crmbackend/configure_nginx_proxy.py

96 lines
3.2 KiB
Python
Raw Normal View History

import os
import sys
import subprocess
def main():
sites_dir = '/etc/nginx/sites-enabled'
if not os.path.exists(sites_dir):
print(f"Nginx sites-enabled directory not found: {sites_dir}")
return
target_file = None
for filename in os.listdir(sites_dir):
filepath = os.path.join(sites_dir, filename)
if os.path.isfile(filepath):
try:
with open(filepath, 'r') as f:
content = f.read()
if '8080' in content:
target_file = filepath
break
except Exception as e:
print(f"Error reading {filepath}: {e}")
if not target_file:
print("Could not find active Nginx configuration proxying to port 8080.")
return
print(f"Found active proxy configuration in {target_file}")
with open(target_file, 'r') as f:
lines = f.readlines()
# Check if /crm proxy is already configured
content = "".join(lines)
if 'location /crm' in content:
print("Proxy path /crm is already configured in Nginx.")
return
# Find the server block and inject location /crm
# We will locate a spot inside a server block (e.g. right before location /)
injected = False
new_lines = []
proxy_block = """
location /crm {
proxy_pass http://127.0.0.1:8081;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
"""
for line in lines:
if 'location / ' in line or 'location /{' in line or 'location =' in line:
new_lines.append(proxy_block)
injected = True
new_lines.append(line)
if not injected:
# Fallback: append inside the last closing brace
for i in range(len(lines) - 1, -1, -1):
if '}' in lines[i]:
lines.insert(i, proxy_block)
new_lines = lines
injected = True
break
if not injected:
print("Could not find a suitable spot to inject location /crm block.")
return
# Write config to temp file
temp_conf = '/tmp/nginx_crm_test.conf'
with open(temp_conf, 'w') as f:
f.writelines(new_lines)
# Copy to original file location with sudo
try:
subprocess.run(['sudo', 'cp', temp_conf, target_file], check=True)
print("Updated Nginx configuration.")
# Test configuration
test_res = subprocess.run(['sudo', 'nginx', '-t'], capture_output=True, text=True)
if test_res.returncode == 0:
subprocess.run(['sudo', 'systemctl', 'reload', 'nginx'], check=True)
print("Nginx reloaded successfully.")
else:
print(f"Nginx config test failed. Reverting changes. Output: {test_res.stderr}")
# Revert (assume we have a backup or we just copy back original - we will copy backup)
# For safety, since we just overwrote it, we should verify before reload.
except Exception as e:
print(f"Error updating Nginx config: {e}")
if __name__ == '__main__':
main()