#!/opt/cloudlinux/venv/bin/python3 -bb
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2020 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENCE.TXT
#


import argparse
import logging

from clwpos.daemon import WposDaemon
from clwpos.daemon_config import load_config
from clwpos.logsetup import init_wpos_sentry_safely, setup_logging

_DAEMON_LOGFILE_PATH = "/var/log/clwpos/daemon.log"


def daemon_main(_opts):
    daemon = WposDaemon()
    if _opts.action == "start":
        daemon.run()
    if _opts.action == "restart":
        daemon.stop(graceful=False)
        daemon.run()
    elif _opts.action == "stop":
        daemon.stop(_opts.graceful)
    elif _opts.action == "reload":
        daemon.reload()
    elif _opts.action == "rolling-restart":
        daemon.request_rolling_restart(_opts.replaced_binary_only)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog='wpos-daemon',
                                     add_help=True,
                                     description='Cloudlinux AccelerateWP daemon')
    parser.add_argument('action',
                        help='start|restart|stop|reload the Cloudlinux AccelerateWP daemon; '
                             'rolling-restart asks the daemon to restart every user\'s redis '
                             'in the background, a few users at a time',
                        choices=['start', 'restart', 'stop', 'reload', 'rolling-restart'])
    parser.add_argument('--graceful', help='use with the "stop" action to cleanup all processes',
                        action='store_true', default=False)
    parser.add_argument('--replaced-binary-only',
                        help='use with the "rolling-restart" action to restart only the redis processes '
                             'whose executable was replaced on disk, e.g. by an alt-redis update',
                        action='store_true', default=False)

    opts = parser.parse_args()

    config = load_config()
    setup_logging(
        caller_name=None,
        console_level=logging.getLevelName(config.logging_level),
        file_level=logging.getLevelName(config.logging_level),
        logfile_path=_DAEMON_LOGFILE_PATH
    )
    init_wpos_sentry_safely()

    daemon_main(opts)
