#!/usr/share/greenos-http-api/bin/python
#
# Copyright GreenOS maintainers and contributors <maintainers@greenos.io>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import grp
import logging
import os
import signal
import sys
from time import sleep

from uvicorn import Config as UvicornConfig
from uvicorn import Server as UvicornServer

from greenos_http_api.app import create_app
from greenos_http_api.config import load_config

CFG_GROUP = "greenoscfg"

LOG = logging.getLogger("http_api")
logs_handler = logging.StreamHandler()
LOG.addHandler(logs_handler)


class ApiServer(UvicornServer):
    def install_signal_handlers(self):
        pass


server = None
shutdown_flag = False


def reload_handler(signum, frame):
    global server
    LOG.debug("Reload signal received...")
    if server is not None:
        server.handle_exit(signum, frame)
        server = None
        LOG.info("Server stopping for reload...")
    else:
        LOG.warning("Reload called for non-running server...")


def shutdown_handler(signum, frame):
    global shutdown_flag
    LOG.debug("Shutdown signal received...")
    if server:
        server.handle_exit(signum, frame)
    LOG.info("Server shutdown...")
    shutdown_flag = True


def main():
    global server, shutdown_flag

    # Set group to greenoscfg so config commits work
    try:
        cfg_group = grp.getgrnam(CFG_GROUP)
        os.setgid(cfg_group.gr_gid)
    except KeyError:
        LOG.warning("Group '%s' not found, running with current gid", CFG_GROUP)

    # File permissions 775 for greenoscfg group write access
    os.umask(0o002)

    signal.signal(signal.SIGHUP, reload_handler)
    signal.signal(signal.SIGTERM, shutdown_handler)

    config = load_config()

    if config.debug:
        LOG.setLevel(logging.DEBUG)
    else:
        LOG.setLevel(logging.INFO)

    while True:
        LOG.debug("Enter main loop...")
        if shutdown_flag:
            break
        if server is None:
            app = create_app(config)
            uvicorn_config = UvicornConfig(
                app,
                uds=config.api_socket_path,
                proxy_headers=True,
                log_level="debug" if config.debug else "info",
            )
            server = ApiServer(uvicorn_config)
            server.run()
        sleep(1)


if __name__ == "__main__":
    main()
