#!/usr/bin/python3
"""Serve the status of the server on the loopback address, behind Caddy, which serves web.port over plain HTTP and
https.web_port over HTTPS.

Run by linux-manager-web.service. Users are managed with linuxmanager_users, the module that
linux-manager-user uses too.

The paths it serves and the modules that answer them are described in the package linuxmanager_web.

The service first initializes, without listening: it makes the signing key, the OpenID Provider's key
(linuxmanager_oidc), the refresh tokens' database (linuxmanager_auth) and the web sites' database (linuxmanager_sites), retrying every INIT_RETRY_SECONDS until all are ready and
logging each failure. Then it listens. Its unit starts it only once wait-for-libpq has found libpq
in the linker cache, where psycopg looks it up.

The service needs nothing else to start and does not end on its own. Every DISCOVERY_SECONDS it
reads web.enabled from /etc/linux-manager/linux-manager.json and listens on
linuxmanager_net.WEB_LOOPBACK_PORT of the loopback address while it is on (linuxmanager_net.web_listen,
linuxmanager_serve.serve). Every request reads what it needs when it is made: the signing
key, the configuration, and the features of the server and the facts shown by /config from
/run/linux-manager/web.json, which linux-manager-setup writes. Before setup has written that file
the server has no features, and /config shows no configuration or interfaces.
"""

import os
import signal
import sys
import threading
import time

sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))

import linuxmanager
import linuxmanager_auth
import linuxmanager_net
import linuxmanager_oidc
import linuxmanager_serve
import linuxmanager_sites
from linuxmanager_web.common import CONFIG_FILE, log, read_json
from linuxmanager_web.handler import Handler
from linuxmanager_web.shell import editor_listen

#: Seconds between two attempts of the initialization.
INIT_RETRY_SECONDS = 15

#: Seconds between two discoveries of where the service should listen.
DISCOVERY_SECONDS = 30


def initialize():
    """Make the signing key, the OpenID Provider's key, the refresh tokens' database and the web sites' database,
    retrying every INIT_RETRY_SECONDS until all are ready."""
    reported = None
    while True:
        phase = 'reading the configuration'
        try:
            cfg = linuxmanager.load_config()
            phase = 'making the signing key'
            linuxmanager_auth.ensure_key()
            phase = 'making the OpenID Provider key'
            linuxmanager_oidc.ensure_key()
            phase = 'creating the token database'
            linuxmanager_auth.provision(cfg)
            phase = 'connecting to the token database'
            with linuxmanager_auth.database(cfg):
                pass
            phase = 'creating the database of the web sites'
            linuxmanager_sites.provision()
            phase = 'connecting to the database of the web sites'
            with linuxmanager_sites.database():
                pass
        except (OSError, SystemExit, linuxmanager_auth.DatabaseError, linuxmanager_sites.DatabaseError) as exc:
            error = f'{phase} failed: {exc.code if isinstance(exc, SystemExit) else exc}'
            if error != reported:
                log(f'{error}; retrying every {INIT_RETRY_SECONDS} seconds')
                reported = error
            time.sleep(INIT_RETRY_SECONDS)
            continue
        log('ready')
        return


def main():
    signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
    initialize()
    threading.Thread(target=editor_listen, name='editor socket', daemon=True).start()
    try:
        linuxmanager_serve.serve(lambda: linuxmanager_net.web_listen(read_json(CONFIG_FILE)), Handler, log,
                                 DISCOVERY_SECONDS)
    except KeyboardInterrupt:
        pass
    return 0


if __name__ == '__main__':
    sys.exit(main())
