#!/bin/bash

#cmd_path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
cmd_path="$(dirname "$(readlink -f "$0")")"
cmd=$1
shift 1

export PYTHONPATH=$PYTHONPATH:${cmd_path}

if [ -z "${cmd}" ]; then

    echo "Dislib: The Distributed Computing Library"
    echo ""
    echo "Usage: dislib COMMAND"
    echo ""
    echo "Available commands:"
    echo "    init [WORK_DIR]:         initializes dislib in the current working dir or in WORK_DIR args is set."
    echo "    kill:                    stops and kills all instances of the dislib."
    echo "    update:                  updates the dislib docker image (use only when installing master branch)."
    echo "    exec FILE [PARAMS]:      executes the FILE inside the container with the given COMPSs [PARAMS]"
    echo "    components list:         lists dislib actives components."
    echo "    components add RESOURCE: adds the RESOURCE to the pool of workers of the dislib."
    echo ""
    echo "       Example given: dislib add worker '127.0.0.1:6' # to add a local worker with 6 computing units."
fi
if [ "${cmd}" == "init" ]; then
    working_dir=$1
    python3 -c "from dislib_cmd import _start_daemon; _start_daemon(working_dir='${working_dir}')"
fi
if [ "${cmd}" == "update" ]; then
    echo "Downloading latest bscwdc/dislib images"
    docker pull bscwdc/dislib:latest
fi
if [ "${cmd}" == "kill" ]; then
    python3 -c "from dislib_cmd import _stop_daemon; _stop_daemon()"
fi
if [ "${cmd}" == "run" ]; then    subcmd=$@
    python3 -c "from dislib_cmd import _exec_in_daemon; _exec_in_daemon('${subcmd}')"
fi
if [ "${cmd}" == "exec" ]; then
    file=$1
    shift 1
    params=$@
    python3 -c "from dislib_cmd import _exec_in_daemon; \
    _exec_in_daemon('runcompss ${params} \
        --lang=python \
        --python_interpreter=python3 \
        --project=/project.xml \
        --resources=/resources.xml \
        ${file}')"
fi
if [ "${cmd}" == "components" ]; then
    subcmd=$@
    python3 -c "from dislib_cmd import _components; _components(arg='${subcmd}')"

fi
