from lib import config as config_module
from lib import logging as logging_lib
from lib import docker_interface
import subprocess
import docker
import os

client = docker_interface.client
config = config_module.config
log = logging_lib.log

def file_exists_in_container(container, file_path):
    """Check if the file exists in the container."""
    exit_code, output = container.exec_run(f"ls {file_path}")
    return exit_code == 0

def copy_file_to_container(container_name, source_path, dest_path):
    """Copy file from host to container using Docker CLI."""
    cmd = f"docker cp {source_path} {container_name}:{dest_path}"
    result = subprocess.run(cmd, shell=True)
    return result.returncode == 0

def run(container_name, host_startup_script_full_path, container_startup_script_full_path):
    try:
        container = client.containers.get(container_name)
        any_err=False
        if not file_exists_in_container(container, container_startup_script_full_path):
            if not copy_file_to_container(container_name, host_startup_script_full_path, container_startup_script_full_path):
                any_err=True
        else:
            with open(f"{host_startup_script_full_path[:-3]}.finished", 'a') as file:
                pass  # No need to write anything, just create the file if it doesn't exist
            return True

        if any_err:
            return False
        else:
            content=''
            with open(host_startup_script_full_path, 'r', encoding='utf-8') as file:
                # Read the content of the file
                content = file.read()
            shell = "/bin/bash" if "#!/bin/bash" in content.split('\n',1)[0] else "/bin/sh"

            response = container.exec_run(cmd=f"{shell} {container_startup_script_full_path}", detach=True)

            with open(f"{host_startup_script_full_path[:-3]}.finished", 'a') as file:
                pass  # No need to write anything, just create the file if it doesn't exist
            return True
    except Exception as e:
        return False