import subprocess
import os

CLOUDDRIVE2_SERVICE_PATH = '/storage/.config/system.d/clouddrive2.service'
CLOUDDRIVE2_SERVICE_CONTENT = """[Unit]
Description=clouddrive2
After=network.target

[Service]
Type=simple
Environment=CLOUDDRIVE_HOME=/storage/Waytech/
WorkingDirectory=/storage/.kodi/addons/plugin.video.clouddrive2
ExecStart=/storage/.kodi/addons/plugin.video.clouddrive2/clouddrive
Restart=on-failure

[Install]
WantedBy=multi-user.target
"""


class SystemctlService:
    def __init__(self, service_name):
        self.service_name = service_name

    def ensure_service_file(self):
        if not os.path.exists(CLOUDDRIVE2_SERVICE_PATH):
            os.makedirs(os.path.dirname(CLOUDDRIVE2_SERVICE_PATH), exist_ok=True)
            with open(CLOUDDRIVE2_SERVICE_PATH, 'w') as f:
                f.write(CLOUDDRIVE2_SERVICE_CONTENT)
            subprocess.run(['systemctl', 'daemon-reload'], check=False)
            return True
        return False

    def start_service(self):
        """启动服务"""
        subprocess.run(['systemctl', 'start', self.service_name], check=True)

    def stop_service(self):
        """停止服务"""
        subprocess.run(['systemctl', 'stop', self.service_name], check=True)

    def enable_service(self):
        """设置开机自启动"""
        subprocess.run(['systemctl', 'enable', self.service_name], check=True)

    def disable_service(self):
        """取消开机自启动"""
        subprocess.run(['systemctl', 'disable', self.service_name], check=True)

    def restart_service(self):
        """重启服务"""
        subprocess.run(['systemctl', 'restart', self.service_name], check=True)
    
    def status_service(self):
        """获取服务状态"""
        result = subprocess.run(['systemctl', 'is-active', self.service_name], capture_output=True, text=True)
        return result.stdout.strip()

    def check_service_status(self):

        try:
            # 检查服务是否正在运行
            result = subprocess.run(
                ['systemctl', 'is-active', self.service_name],
                capture_output=True,
                text=True
            )
            if result.stdout.strip() == 'active':
                return "on"
            else:
                return "off"
        except subprocess.CalledProcessError:
            # 如果服务不存在或命令执行失败，返回 "关闭"
            return "服务不存在"