#!/bin/bash
lockfiles=()
scratch="/scratch"
while [ "$1" != "--" ]; do
    dataset_file="$1"
    filename=$(basename -- "${dataset_file}")
    dataset_name="${filename%%.*}"
    destination="${scratch}/${dataset_name}"
    lockfile="${destination}.lock"
    lockfiles+=("${lockfile}")

    # Try to get lock
    if lockfile -r 0 "${lockfile}"; then
        # We got the lock, thus we should extract the data if it does not exist already.
        echo Got lock "${lockfile}"
        if [ ! -d "${destination}" ]; then
            echo Extracting data
            tar -xf "${dataset_file}" -C "${scratch}"
        else
            echo Data already extracted skipping.
        fi
        rm -f "${lockfile}"
    fi
    shift
done
shift

for lockfile in "${lockfiles[@]}"; do
    # The data is either already being extracted by annother process or has already been extracted.
    echo -n "Waiting for lockfile ${lockfile} to be removed."
    while [ -f "${lockfile}" ]; do
        echo -n "."
        sleep 10
    done
    echo
done
export DATA_PATH="${scratch}"
echo "$@"
"$@"
