import logging


def get_cluster_scratch_dir_from_script(cluster_script_filepath):
    """
    Get cluster scratch directory from cluster script

    The cluster scratch directory is where all job data is saved while the job
    is running. This directory also contains the README.

    The cluster script typically only one line with a shell command like:
    `cd /W01_cluster_scratch/1234567*`

    Parameters
    ----------
    cluster_script_filepath : str
        Filepath of the cluster script from which to retrieve the cluster
        scratch directory.

    Returns
    -------
    str or None
        Directory path of the cluster scratch directory found in the script.
        Globbing is applied to the string. So the directory should exist.
        If no directory is found, return is None
    """

    logger = logging.getLogger(__name__).getChild(
        "get_cluster_scratch_dir_from_script")
    # logger = logging.getLogger("poll_jobs.get_cluster_scratch_dir_from_script")
    logger.info("Getting scratch dir from cluster script: {}".format(
        cluster_script_filepath))

    cluster_scratch_path = None

    try:
        with open(cluster_script_filepath, "r") as f:
            # Reding the first line
            line = f.readline()
    except (FileNotFoundError, PermissionError) as err_msg:
        logger.error(err_msg)
        logger.error("Cluster script not found or no access."
                     " Can not check for cluster scratch dir.")
    else:
        if "cd" in line:
            line_split = line.split(" ")
            if len(line_split) > 1:
                # The strip() is necessary is to remove the trailing newline
                # that is included in the clusterscript files in production.
                cluster_scratch_path = line_split[1].strip()
                if cluster_scratch_path.endswith("*"):
                    cluster_scratch_path = cluster_scratch_path[:-1]

    if cluster_scratch_path:
        logger.info("Cluster scratch directory found: {}".format(
            cluster_scratch_path))
        return cluster_scratch_path
    else:
        logger.info("No cluster scratch directory found")
        return None