#!/usr/bin/env bash

#
# Get a login for a docker container.
#

die() {
    echo $@
    exit 1
}

usage() {
    cat <<EOF
dssh: log in to a docker node

usage: dssh: [options]

options:
-h:           show this help message.
-i [ID]:      ssh into a docker node with this container ID
-n [name]:    ssh into a docker node with this name
-t [0 or 1]:  0 to avoid allocating a TTY; 1 to allocate one.
              The default will be set based on whether this appears
              to be an interactive shell.
EOF
}

DOCKER_IMAGE_ID=""
DOCKER_IMAGE_NAME=""
if [ -t 0 ]; then
    ALLOCATE_TTY=1
else
    ALLOCATE_TTY=0
fi
while getopts  "hi:n:t:" flag; do
    case $flag in
    h) usage; exit 0;;
    i) DOCKER_IMAGE_ID=${OPTARG};;
    n) DOCKER_IMAGE_NAME=${OPTARG};;
    t) ALLOCATE_TTY=${OPTARG};;
    *) echo "getopts error"
        echo
        usage
        exit 1;;
    esac
done
shift $(expr $OPTIND - 1)
if [ $# -eq 0 ]; then
    RUN_COMMAND="/bin/bash"
else
    RUN_COMMAND=""
fi

which docker &>/dev/null || die "docker must be on the PATH."

if [ "x${DOCKER_IMAGE_NAME}" == "x" ]; then
    if [ "x${DOCKER_IMAGE_ID}" == "x" ]; then
        usage
        exit 1
    fi
else
    if [ "x${DOCKER_IMAGE_ID}" == "x" ]; then
        :
    else
        echo "You must not supply both an ID and a name."
        exit 1
    fi
    DOCKER_IMAGE_ID=$(docker ps -f name=${DOCKER_IMAGE_NAME} -q)
    [ "x${DOCKER_IMAGE_ID}" == "x" ] && \
        die "failed to find a docker image named ${DOCKER_IMAGE_NAME}"
fi

if [ ${ALLOCATE_TTY} == 1 ]; then
    docker exec -it "${DOCKER_IMAGE_ID}" "${@}" ${RUN_COMMAND}
else
    docker exec -i "${DOCKER_IMAGE_ID}" "${@}" ${RUN_COMMAND} &
    wait
fi