#!/opt/alt/python37/bin/python3 -bb
# coding=utf-8
#
# 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
#

# Cloudlinux + sender daemon control utility

import sys
from clcommon.lib.jwt_token import jwt_token_check
import subprocess
import os

DISABLE_DIR = "/etc/cl_plus"
DISABLE_FILE = os.path.join(DISABLE_DIR, ".disabled")
ENABLE_CRON_FILE = os.path.join(DISABLE_DIR, ".cron_enabled")
SETUP_CLPLUS_FILE = '/usr/share/cloudlinux/cl_plus/setup_clplus'


def main():
    if '--help' in sys.argv:
        print(
            "--help - will show this page\n"
            "enable - [default] will turn on cl_plus service (this option will remove file '/etc/cl_plus/.disable')\n"
            "disable - will turn off cl_plus service (this option will add file '/etc/cl_plus/.disable')"
        )
        sys.exit(0)
    if 'enable' in sys.argv:
        try:
            os.remove(DISABLE_FILE)
        except OSError:
            pass
        if not os.path.isdir(DISABLE_DIR):
            os.mkdir(DISABLE_DIR, 0o644)
        # create cron manage file
        open(ENABLE_CRON_FILE, "w+").close()
    elif 'disable' in sys.argv:
        # remove cron manage file
        try:
            os.remove(ENABLE_CRON_FILE)
        except OSError:
            pass
        # create .disable file
        if not os.path.isdir(DISABLE_DIR):
            os.mkdir(DISABLE_DIR, 0o644)
        open(DISABLE_FILE, "w+").close()
    else:
        # in case we run this script from cron without params
        if not os.path.isfile(ENABLE_CRON_FILE):
            print("Cron enable file does not found")
            sys.exit(0)

    is_valid, _, _ = jwt_token_check()
    is_disabled = os.path.isfile(DISABLE_FILE)
    if not is_valid or is_disabled:
        # JWT token absent or invalid - remove daemons
        if os.path.isfile(SETUP_CLPLUS_FILE):
            subprocess.call(["yum", "-y", "remove", "cl-end-server-tools"])
        sys.exit(0)
    # JWT token check OK - install daemons
    if not os.path.isfile(SETUP_CLPLUS_FILE):
        subprocess.call(["yum", "-y", "install", "cl-end-server-tools", "--enablerepo", "cloudlinux-updates-testing"])


if __name__ == "__main__":
    main()
