#!/usr/bin/python3

import argparse
import subprocess
import sys

class ServiceReloader:
    def __init__(self, ctl_sctipt_name: str):
        self.__ctl_sctipt_name = ctl_sctipt_name

    def reload_if_active(self) -> int:
        try:
            if self.__is_service_active():
                self.__disable_service()
                self.__enable_service()
            return 0
        except Exception as e:
            print(str(e))
            return 2

    def __is_service_active(self) -> bool:
        result = subprocess.run(
            [self.__ctl_sctipt_name, "status"],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )

        return result.returncode == 0

    def __disable_service(self) -> None:
        self.__exec_ctl_command("disable")

    def __enable_service(self) -> None:
        self.__exec_ctl_command("enable")

    def __exec_ctl_command(self, command: str) -> bool:
        result = subprocess.run(
            [self.__ctl_sctipt_name, command],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=True
        )

        return result.returncode == 0

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "command",
        choices=["reload_if_active"],
        help="Switch log level to debug and back"
    )
    return parser.parse_args()

def main():
    args = parse_args()

    if args.command == "reload_if_active":
        reloader = ServiceReloader("/usr/sbin/astra-update-ctl")
        return reloader.reload_if_active()
    else:
        return 1

sys.exit(main())
