from zscams.agent.src.support.filesystem import append_to_file
from zscams.agent.src.support.logger import get_logger


logger = get_logger("ssh_support")


def add_to_known_hosts(user: str, hostname: str, pub_key: str):
    try:
        logger.debug("Appending '%s' to known hosts...", pub_key)
        append_to_file(
            f"/home/{user}/.ssh/known_hosts",
            f"{hostname} {pub_key}\n",
        )
        logger.debug("Appended key to known hosts")
    except:
        pass


def add_to_authorized_keys(user: str, pub_key: str):
    logger.debug("Appending to public key to %s", user)
    key = pub_key.split(" ")[1] if len(pub_key.split(" ")) >= 2 else pub_key
    try:
        file = f"/home/{user}/.ssh/authorized_keys"
        append_to_file(
            file,
            f"ssh-rsa {key} zscams@orangecyberdefense\n",
        )
        logger.info("Appended pub key for %s to %s", user, file)
    except:
        pass
