import os
import socket
import json
import subprocess
import logging
import stat

# Configuración de logging
logging.basicConfig(level=logging.INFO, filename='/var/log/oglive_daemon.log', filemode='a', format='%(asctime)s - %(levelname)s - %(message)s')

def handle_command(command):
    action = command.get('action')
    args = command.get('args', [])
    cleaned_args = [arg.strip('\'"') for arg in args]
    logging.info(f'Handling command: {action} with args: {cleaned_args}')

    try:
        if action in ['config', 'install', 'download', 'show', 'check', 'uninstall', 'disk_usage','list_installed_oglives','get_info','get_default','set_default','check_services_status']:
            command_to_run = ['sudo', '/opt/ogboot/bin/oglivecli', action] + cleaned_args
            logging.info(f'Running command: {" ".join(command_to_run)}')
            process = subprocess.Popen(command_to_run, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            stdout, stderr = process.communicate()
            logging.info(f'Command stdout: {stdout}')
            logging.error(f'Command stderr: {stderr}')

            # Asumimos que `stdout` contendrá el JSON válido
            try:
                json_output = json.loads(stdout)
                return {"success": True, "output": json_output}
            except json.JSONDecodeError as e:
                logging.error(f'Error parsing JSON: {e} - Raw output: {stdout}')
                return {"success": False, "error": f'Error parsing JSON: {str(e)} - Raw output: {stdout}'}

        else:
            return {"success": False, "error": "Unknown command"}
    except Exception as e:
        logging.error(f'Error handling command {action}: {e}')
        return {"success": False, "error": str(e)}

def main():
    # Crea el directorio si no existe
    if not os.path.exists('/var/run/oglive'):
        os.makedirs('/var/run/oglive', exist_ok=True)

    socket_path = '/var/run/oglive/oglive_daemon.sock'

    # Elimina el socket si existe
    if os.path.exists(socket_path):
        os.remove(socket_path)

    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server.bind(socket_path)

    # Establece los permisos del socket
    os.chmod(socket_path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # Permisos para todos los usuarios

    server.listen()

    try:
        while True:
            logging.info('Daemon ready to accept connections')
            conn, _ = server.accept()
            with conn:
                logging.info('Accepted connection')
                data = conn.recv(1024)
                if not data:
                    continue
                try:
                    command = json.loads(data.decode('utf-8'))
                    logging.info(f'Received command: {command}')
                except json.JSONDecodeError:
                    logging.error('Failed to decode JSON')
                    conn.sendall(json.dumps({"success": False, "error": "Invalid JSON"}).encode('utf-8'))
                    continue

                response = handle_command(command)
                conn.sendall(json.dumps(response).encode('utf-8'))
    finally:
        server.close()
        if os.path.exists(socket_path):
            os.remove(socket_path)

if __name__ == '__main__':
    main()

