#!/opt/cloudlinux/venv/bin/python3 -sbb
# coding:utf-8

# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2023 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys
import time
import json
import glob
import argparse
from enum import Enum
from ui_package_installer import UIPackageInstaller, State
from clcommon.cpapi import Feature, is_panel_feature_supported
from clcommon.ui_config import UIConfig
from clcommon.lib.cledition import is_cl_shared_pro_edition
from clcommon.utils import is_ubuntu

PACKAGE_NAME = "cloudlinux-awp-plugin"
PACKAGE_PATH = "/usr/share/cloudlinux-awp-plugin"
PACKAGE_INSTALL_ERROR_LOG = "/var/log/awp_install_error.log"
FLAGS_DIR = "/var/lve/clflags"
CL_WIZARD_FINISHED_FLAG = "/var/lve/wizard/done.flag"

# Flags
FLAGS = {
    "enable_awp_all_servers": "/var/lve/clflags/enable_awp_all_servers.flag",
    "enable_awp_this_server": "/var/lve/clflags/enable_awp_this_server.flag",
    "skip_awp_setup": "/var/lve/clflags/skip_awp_setup.flag"
}

class AWPUIPackageInstaller(UIPackageInstaller):
    def __init__(self, package_name, package_path, error_log_path):
        super().__init__(package_name, package_path, error_log_path)
        self.activation_options = list(FLAGS.keys())

        # Args
        self.parser = argparse.ArgumentParser(description="AccelerateWP wizard")
        self.parser.add_argument("-i", "--install", action="store_true", help="Install cloudlinux-awp-plugin")
        self.parser.add_argument("-c", "--check", action="store_true", help="Check installation progress")
        self.parser.add_argument("-l", "--log", action="store_true", help="Get installation logs")
        self.parser.add_argument("-a", "--activation", choices=self.activation_options, help="Record activation choice")
        self.parser.add_argument("-s", "--status", action="store_true", help="Get status including setup requirements")

    def run(self):
        args = self.parser.parse_args()

        if not any(vars(args).values()):
            self.parser.print_help()
            return

        result = None
        if args.install:
            result = self.install().value
        elif args.check:
            result = self.check_installed().value
        elif args.log:
            result = self.get_log()
        elif args.activation:
            result = self.activation(args.activation)
        elif args.status:
            result = self.activation_status()

        print(json.dumps({
            "result": "success",
            "timestamp": time.time(),
            "response": result
        }))

    def clear_old_flags(self):
        """
        Cleanup flags if they exists
        """
        for flag in FLAGS.values():
            try:
                if os.path.isfile(flag):
                    os.remove(flag)
            except Exception:
                pass

    def create_flag(self, option):
        """
        Create flag file which represents what choice customer done on setup page.
        """
        with open(FLAGS[option], "w") as file:
            pass

    def is_setup_done(self):
        """
        Check if setup already done
        """
        for flag in FLAGS.values():
            if os.path.isfile(flag):
                return True
        return False

    def is_cl_wizard_finished(self):
        """
        Check if cloudlinux wizard finished
        """
        return os.path.isfile(CL_WIZARD_FINISHED_FLAG)

    def is_supported_edition(self):
        """
        Check if cloudlinux edition supports AccelerateWP
        """
        if is_cl_shared_pro_edition(skip_jwt_check=True):
            return True
        return False

    def is_awp_supported(self):
        """
        Check if AccelerateWP is supported based on edition and supported features
        """
        if self.is_supported_edition() and is_panel_feature_supported("accelerate_wp"):
            return True
        return False

    def is_setup_required(self):
        """
        Check if setup required
        """
        if not self.is_awp_supported() or self.is_setup_done() or not self.is_cl_wizard_finished():
            return False
        if self.check_installed().value == State.NOT_INSTALLED \
           or UIConfig().get_param("hideAccelerateWPApp", "uiSettings") is True:
            return True
        return False

    def activation(self, activation_option):
        """
        Cleanup old flags and create new one depending on user choice
        """
        if not os.path.exists(FLAGS_DIR):
            os.makedirs(FLAGS_DIR)
        self.clear_old_flags()
        self.create_flag(activation_option)
        return activation_option

    def activation_status(self):
        """
        Return status of setup requirements and installation status
        """
        return {
            "status": self.check_installed().value,
            "is_setup_required": self.is_setup_required()
        }


def main():
    installer = AWPUIPackageInstaller(PACKAGE_NAME, PACKAGE_PATH, PACKAGE_INSTALL_ERROR_LOG)
    installer.run()


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(json.dumps({"result": "error", "timestamp": time.time(), "response": str(error)}))
        sys.exit(1)
