#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys

SETTINGS_FILE = "/var/openfw/emailrelay/settings"
USERS_FILE    = "/var/openfw/emailrelay/users"
AUTH_CFG      = "/etc/emailrelay.auth"
USERS_CFG     = "/etc/emailrelay.users"
CONF_FILE     = "/etc/emailrelay.conf"
START_LOCAL   = "/var/efw/inithooks/start.local"
RELAY_BIN     = "/usr/local/bin/setemailrelay"

def get_settings():
    settings = {}
    if os.path.exists(SETTINGS_FILE):
        with open(SETTINGS_FILE, 'r') as f:
            for line in f:
                if '=' in line:
                    key, val = line.strip().split('=', 1)
                    settings[key] = val
    return settings

def get_existing_password():
    if os.path.exists(AUTH_CFG):
        with open(AUTH_CFG, 'r') as f:
            content = f.read().split()
            if len(content) >= 4:
                return content[3]
    return ""

def process_users():
    if not os.path.exists(USERS_FILE):
        open(USERS_CFG, 'w').close()
        os.chmod(USERS_CFG, 0600)
        os.system("chown nobody:nogroup %s" % USERS_CFG)
        return

    existing = {}
    if os.path.exists(USERS_CFG):
        with open(USERS_CFG, 'r') as f:
            for line in f:
                parts = line.strip().split()
                if len(parts) >= 4:
                    existing[parts[2]] = parts[3]

    entries = []
    usernames_only = []

    with open(USERS_FILE, 'r') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            parts = line.split(':', 1)
            username = parts[0].strip()
            password = parts[1].strip() if len(parts) > 1 else ''

            if not username:
                continue

            if password == '' or password == '********':
                password = existing.get(username, '')

            entries.append((username, password))
            usernames_only.append(username)

    with open(USERS_CFG, 'w') as f:
        for username, password in entries:
            f.write("server plain %s %s\n" % (username, password))

    os.chmod(USERS_CFG, 0600)
    os.system("chown nobody:nogroup %s" % USERS_CFG)

    with open(USERS_FILE, 'w') as f:
        for username in usernames_only:
            f.write("%s\n" % username)

    os.chmod(USERS_FILE, 0644)
    os.system("chown nobody:nogroup %s" % USERS_FILE)

def configure_start_local(enabled):
    if enabled:
        if os.path.exists(START_LOCAL):
            with open(START_LOCAL, 'r') as f:
                lines = f.readlines()
            if not any(RELAY_BIN in line for line in lines):
                with open(START_LOCAL, 'a') as f:
                    f.write("%s\n" % RELAY_BIN)
        else:
            with open(START_LOCAL, 'w') as f:
                f.write("#!/bin/bash\n")
                f.write("%s\n" % RELAY_BIN)
            os.chmod(START_LOCAL, 0755)
    else:
        if os.path.exists(START_LOCAL):
            with open(START_LOCAL, 'r') as f:
                lines = f.readlines()
            with open(START_LOCAL, 'w') as f:
                for line in lines:
                    if RELAY_BIN not in line:
                        f.write(line)

def main():
    settings = get_settings()

    if settings.get('SERVER_ENABLED') != 'on':
        os.system("/etc/init.d/emailrelay stop")
        configure_start_local(False)
        return

    password = settings.get('SMARTHOST_PASSWORD', '')
    if not password:
        password = get_existing_password()

    auth_mechanism = settings.get('SMARTHOST_AUTH_MECHANISMS', 'PLAIN').strip().lower()
    if auth_mechanism not in ('plain', 'login'):
        auth_mechanism = 'plain'

    with open(AUTH_CFG, 'w') as f:
        f.write("client %s %s %s" % (auth_mechanism, settings.get('SMARTHOST_ACCOUNT'), password))

    os.chmod(AUTH_CFG, 0600)
    os.system("chown nobody:nogroup %s" % AUTH_CFG)

    if os.path.exists(SETTINGS_FILE):
        with open(SETTINGS_FILE, 'r') as f:
            lines = f.readlines()
        with open(SETTINGS_FILE, 'w') as f:
            for line in lines:
                if not line.startswith("SMARTHOST_PASSWORD="):
                    f.write(line)

    process_users()

    with open(CONF_FILE, 'w') as f:
        f.write("as-server\n")
        f.write("port %s\n" % settings.get('SERVER_PORT'))

        if settings.get('SERVER_LOCALHOST_ONLY') == 'on':
            f.write("interface 127.0.0.1\n")

        f.write("spool-dir /var/spool/emailrelay\n")
        f.write("log-file /var/log/emailrelay/emailrelay.log\n")
        f.write("pid-file /var/run/emailrelay/emailrelay.pid\n")
        f.write("user nobody\n")

        if settings.get('SERVER_AUTH') == 'on':
            f.write("server-auth %s\n" % USERS_CFG)

        f.write("client-auth %s\n" % AUTH_CFG)
        f.write("forward-on-disconnect\n")
        f.write("forward-to %s:%s\n" % (
            settings.get('SMARTHOST_SERVER'),
            settings.get('SMARTHOST_PORT')
        ))

        if settings.get('SMARTHOST_TLS') == 'on':
            f.write("client-tls\n")
        if settings.get('SERVER_VERBOSE') == 'on':
            f.write("verbose\n")

    configure_start_local(True)
    os.system("/etc/init.d/emailrelay restart")

if __name__ == "__main__":
    main()