#!/usr/bin/python3
"""Initialize Listmonk privately before enabling its public proxy."""

import argparse
import ipaddress
import json
import os
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

READY = Path('/etc/listmonk/ready')
IN_PROGRESS = Path('/etc/listmonk/setup-in-progress')
CONFIG = '/etc/listmonk/config.toml'
FINAL_DB = 'listmonk'
STAGE_DB = 'listmonk_setup'


def service_environment(user, home):
    """Do not pass root-only provisioning values to unprivileged services."""
    return {'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
            'HOME': home, 'USER': user, 'LOGNAME': user, 'LANG': 'C.UTF-8'}


def host_url(value):
    """Accept a host, not a URL or an nginx/SQL fragment."""
    if not value or value == 'DEFAULT' or len(value) > 253:
        raise ValueError('Enter the server hostname or IP address')
    try:
        address = ipaddress.ip_address(value)
    except ValueError:
        labels = value.rstrip('.').split('.')
        if any(not re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?',
                                label) for label in labels):
            raise ValueError('Enter a valid hostname or IP address')
        return 'https://' + value.rstrip('.')
    return 'https://[' + value + ']' if address.version == 6 else 'https://' + value


def expression(value):
    """Pass arbitrary UTF-8 data without putting it in process arguments."""
    return "convert_from(decode('%s','hex'),'UTF8')" % value.encode('utf-8').hex()


def psql(database, statement):
    result = subprocess.run(
        ['psql', '-X', '-qAt', '-v', 'ON_ERROR_STOP=1', '-d', database],
        input=statement + '\n', text=True, user='postgres', group='postgres',
        extra_groups=[], env=service_environment('postgres', '/var/lib/postgresql'),
        capture_output=True, check=True)
    return result.stdout.strip()


def db_exists(name):
    return psql('postgres', "SELECT 1 FROM pg_database WHERE datname=" +
                expression(name) + ';') == '1'


def verify_admin(database, password):
    statement = ("SELECT count(*) FROM users u JOIN roles r ON r.id=u.user_role_id "
                 "WHERE u.username='admin' AND u.status='enabled' "
                 "AND u.password_login AND r.name='Super Admin' "
                 "AND u.password=crypt(" + expression(password) + ",u.password);")
    return psql(database, statement) == '1'


def verify_configuration(database, url, email):
    statement = ("SELECT count(*) FROM settings s JOIN users u ON u.username='admin' "
                 "WHERE s.key='app.root_url' AND s.value=to_jsonb(" +
                 expression(url) + ") AND u.email=" + expression(email) + ';')
    return psql(database, statement) == '1'


def initial_settings(url, email):
    # This applies only to the private, newly-created staging database.
    smtp = [{"enabled": True, "host": "127.0.0.1", "port": 25,
             "auth_protocol": "none", "username": "", "password": "",
             "hello_hostname": "", "max_conns": 1, "idle_timeout": "15s",
             "wait_timeout": "5s", "max_msg_retries": 2,
             "msg_retry_delay": "10ms", "tls_type": "none",
             "tls_skip_verify": False, "email_headers": [],
             "from_addresses": []}]
    values = {'app.root_url': url, 'app.from_email': email, 'smtp': smtp}
    statements = []
    for key, value in values.items():
        payload = json.dumps(value, ensure_ascii=False, separators=(',', ':'))
        statements.append("UPDATE settings SET value=" + expression(payload) +
                          "::jsonb WHERE key=" + expression(key) + ';')
    statements.extend([
        "UPDATE users SET email=" + expression(email) + " WHERE username='admin';",
        'DELETE FROM campaigns;', 'DELETE FROM subscribers;', 'DELETE FROM lists;',
    ])
    psql(STAGE_DB, 'BEGIN;\n' + '\n'.join(statements) + '\nCOMMIT;')


def start_service():
    subprocess.run(['systemctl', 'start', 'listmonk'], check=True)
    for attempt in range(30):
        try:
            with urllib.request.urlopen('http://127.0.0.1:9000/admin/login', timeout=2) as response:
                if response.status == 200:
                    return
        except (OSError, urllib.error.URLError):
            pass
        if attempt < 29:
            time.sleep(1)
    raise RuntimeError('Listmonk did not start; retry setup after checking the service')


def setup(password, domain, email):
    if READY.exists():
        start_service()
        return
    url = host_url(domain)
    if not password or len(password) < 8 or any(ch in password for ch in '\x00\r\n'):
        raise ValueError('Use a password of at least eight characters on one line')
    if password != password.strip():
        raise ValueError('Remove leading and trailing whitespace from the password')
    if len(password.encode('utf-8')) > 72:
        raise ValueError('Use a password of at most 72 UTF-8 bytes')
    if not email or not re.fullmatch(r'[^@\s]+@[^@\s]+\.[^@\s]+', email):
        raise ValueError('Enter a valid administrator email address')

    final_exists = db_exists(FINAL_DB)
    stage_exists = db_exists(STAGE_DB)
    if not IN_PROGRESS.exists():
        if final_exists or stage_exists:
            raise RuntimeError('An existing Listmonk database needs manual recovery')
        fd = os.open(IN_PROGRESS, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
        os.close(fd)
    if not final_exists:
        if stage_exists:
            # Only our private, never-published staging database is retried.
            psql('postgres', 'DROP DATABASE listmonk_setup WITH (FORCE);')
        psql('postgres', 'CREATE DATABASE listmonk_setup OWNER listmonk;')
        # The installer runs as listmonk and must not inherit root-only
        # provisioning credentials from the firstboot environment.
        env = service_environment('listmonk', '/var/lib/listmonk')
        env.update(LISTMONK_ADMIN_USER='admin', LISTMONK_ADMIN_PASSWORD=password,
                   LISTMONK_db__database=STAGE_DB)
        subprocess.run(['/usr/local/bin/listmonk', '--install', '--yes',
                        '--idempotent', '--config', CONFIG], user='listmonk',
                       group='listmonk', extra_groups=[], cwd='/var/lib/listmonk',
                       env=env, check=True)
        initial_settings(url, email)
        if not verify_admin(STAGE_DB, password):
            raise RuntimeError('The initial administrator could not be verified')
        if not verify_configuration(STAGE_DB, url, email):
            raise RuntimeError('The initial address and email could not be verified')
        psql('postgres', 'ALTER DATABASE listmonk_setup RENAME TO listmonk;')
    elif not verify_admin(FINAL_DB, password):
        raise RuntimeError('Setup was interrupted; enter the original administrator password')
    elif not verify_configuration(FINAL_DB, url, email):
        raise RuntimeError('Setup was interrupted; enter the original address and email')

    from libinithooks import inithooks_cache
    inithooks_cache.write('APP_DOMAIN', domain)
    inithooks_cache.write('APP_EMAIL', email)
    fd = os.open(READY, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
    os.close(fd)
    IN_PROGRESS.unlink()
    start_service()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    password_input = parser.add_mutually_exclusive_group()
    password_input.add_argument('--pass-stdin', action='store_true')
    password_input.add_argument('--pass-fd', type=int)
    parser.add_argument('--domain', default='')
    parser.add_argument('--email', default='')
    args = parser.parse_args()
    password = ''
    if not READY.exists():
        if args.pass_stdin:
            password = sys.stdin.readline().rstrip('\r\n')
        elif args.pass_fd is not None:
            with os.fdopen(args.pass_fd, 'r', encoding='utf-8') as stream:
                password = stream.readline().rstrip('\r\n')
    if not READY.exists() and (not password or not args.domain or args.domain == 'DEFAULT' or not args.email):
        if not sys.stdin.isatty():
            print('Listmonk setup needs an administrator password, public address and email; '
                  'provide them in the preseed or complete setup at first login.', file=sys.stderr)
            raise SystemExit(1)
        from libinithooks.dialog_wrapper import Dialog
        dialog = Dialog('TurnKey Linux - First boot configuration')
        if not password:
            password = dialog.get_password('Listmonk administrator',
                'Enter the password for the Listmonk admin account.',
                pass_req=8, min_complexity=4)
        if not args.domain or args.domain == 'DEFAULT':
            args.domain = dialog.get_input('Listmonk address',
                'Enter the hostname or IP address used to reach Listmonk.', '')
        if not args.email:
            args.email = dialog.get_email('Listmonk email',
                'Enter the administrator email address.', '')
    try:
        setup(password, args.domain, args.email)
    except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError) as exc:
        # Subprocess output is deliberately omitted because it may contain secrets.
        print('Listmonk setup failed: ' + (str(exc) if isinstance(exc, (ValueError, RuntimeError))
              else 'check the database and service, then retry setup'), file=sys.stderr)
        raise SystemExit(1) from None


if __name__ == '__main__':
    main()
