#!/bin/bash -e

PARAMS="$@"

PANDIR=${PANDIR:-/var/panoptes}

cd "${PANDIR}"

# TODO Detect and install docker if needed.
# TODO Detect and install docker-compose if needed.

IMAGE="${IMAGE:-gcr.io/panoptes-exp/panoptes-utils}"
TAG="${TAG:-develop}"

CMD="docker-compose \
    --project-directory ${PANDIR} \
    -f panoptes-utils/docker/docker-compose-develop.yaml \
    -p panoptes"

# If user only asked to start, check if already running and if so use "-d" option.
if [[ "$PARAMS" == "up" ]]; then
    PARAMS="up -d"
fi

# Run the docker-compose command with user params.
eval "IMAGE=${IMAGE} TAG=${TAG} ${CMD} ${PARAMS}"

if [[ "$PARAMS" == "up -d" ]]; then
    # Prompt for password
    "${PANDIR}/panoptes-utils/bin/wait-for-it.sh" \
        localhost:8888 \
        -- \
        docker exec -it -u panoptes develop-env jupyter notebook list | grep http | cut -d ' ' -f 1 | xargs xdg-open
fi
