#!/usr/bin/python3
import os
#
# Copyright (C) 2022 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#

import sys
import nsmigration
from nethsec import reverse_proxy

(u, data, nmap) = nsmigration.init("reverse_proxy.json")

if 'server' not in data and 'locations' not in data:
    sys.exit(0)

# ensure the custom_certs directory exists
if not os.path.isdir('/etc/nginx/custom_certs'):
    os.mkdir('/etc/nginx/custom_certs')
# loop over server
for server in data['servers']:
    # get server data
    server_name = server['server_name']
    description = server['uci_description']
    ssl_certificate = server['ssl_certificate']
    ssl_certificate_key = server['ssl_certificate_key']
    destination = server['locations'][0]['proxy_pass']
    allow = server['locations'][0]['allow']

    # generate list of available certificates, every loop in case a new one was added
    available_certs = {}
    for entry in os.scandir('/etc/nginx/custom_certs'):
        if entry.is_file() and entry.name.endswith('.crt') and os.path.isfile(entry.path[:-4] + '.key'):
            available_certs[entry.name[:-4]] = {
                'cert_content': open(entry.path, 'r').read(),
                'key_content': open(entry.path[:-4] + '.key', 'r').read(),
            }

    # check if the certificate is already available
    certificate = ''
    for name, entry in available_certs.items():
        if ssl_certificate == entry['cert_content'] and ssl_certificate_key == entry['key_content']:
            certificate = name
            break
    if certificate == '':
        # certificate is not available, import it
        with open(f'/etc/nginx/custom_certs/{server_name}.crt', 'w') as fp:
            fp.write(ssl_certificate)
        with open(f'/etc/nginx/custom_certs/{server_name}.key', 'w') as fp:
            fp.write(ssl_certificate_key)
        certificate = server_name

    # import server
    reverse_proxy.add_domain(server_name, destination, certificate, description, allow)

for location in data['locations']:
    # get location data
    path = location['location']
    description = location['uci_description']
    destination = location['proxy_pass']
    allow = location['allow']

    # import location
    reverse_proxy.add_path(path, destination, description, allow)

# Save configuration
u.commit('nginx')
