#!/bin/bash
WORKING_DIR="$1"

# Make sure the working directory exists
if [ ! -d "$WORKING_DIR" ]; then
    echo "[fatal] the working directory does not exist: $WORKING_DIR" 1>&2
    exit 1
fi

current_dir="$PWD"
cd "$WORKING_DIR"

# Now make sure the run.log exists, I will get the paths to the runs from here
RUN_LOG="./run.log"

# Make sure the working directory exists
if [ ! -r "$RUN_LOG" ]; then
    echo "[fatal] the run.log is not readable: $RUN_LOG" 1>&2
    exit 1
fi

# Now extract the various log locations from the run log
# TODO: I should make this more robust and search for column names not numbers 
for i in $(tail -n+2 "$RUN_LOG" | cut -f6 ); do
    # ignore the initialisation entry
    if [ "$i" == "INIT" ]; then
        continue
    fi

    tar_path="./$i"
    tar_file="$tar_path".tar.gz

    # If we can't find the directory...it could be because a file has 
    # already been created in a previous run, but if we can't find that
    # then it is an error
    if [[ ! -d "$tar_path" ]] && [[ ! -e "$tar_file" ]]; then
        echo "[fatal] can't find log directory: $tar_path or any tar files" 1>&2
        exit 1
    fi

    # Only attempt tar if the run directory exists, it may have been
    # tarred already
    if [[ -d "$tar_path" ]]; then
	echo "[info] tarring: $tar_path to $tar_file"
	tar -czf "$tar_file" "$tar_path"
	
	if [[ $? -ne 0 ]] || [[ ! -e "$tar_file" ]]; then
            echo "[warning] tar did not exit cleanly or tar file does not exist, not deleting directory: $tar_path"
            continue
	fi

	echo "[info] removing $tar_path"
	rm -r "$tar_path"
    fi
done

cd "$current_dir"

echo "*** END ***"

