#!/bin/bash

function printUsage() {
    cat <<EOF
Usage: voxl-docker -i [IMAGE] [ARGUMENTS]

This is a helper script to make 'docker run' faster to use by incorperating the
most common options when using docker on VOXL.

By default this mounts yocto's home directory /home/root inside the docker
container at /root/yoctohome for easy access to files outside the docker.
The directory that gets mounted inside the docker can be manually
specified with the -d argument.

Also mounts /etc/modalai/ inside the docker container so applications can read
settings and configuration.

Also mounts /run/mpa/ inside the docker container so applications can access MPA.

Also mounts /data/ inside the docker so large file storage is available.

ARGUMENTS:
  -i <name>: Docker image to run, e.g. roskinetic
  -d <name>: Dir to mount as /root/yoctohome/ inside docker.
  -n       : disable interactive mode (enabled by default)
  -w       : set working directory, /root/ by default
  -e       : set the entrypoint for the docker image launch

  -l       : list installed docker images
  -h:      : Print this help message

Typical example:

voxl-docker -i roskinetic

EOF
    exit 1
}


MOUNT="/home/root"
IMAGE=""
USER_OPTS=""
MOUNT_OPTS=""
ENTRYPOINT="/bin/bash"
INTERACTIVE="-it"
WORKING_DIR="/root/"


# parse arguemnts
while getopts 'hd:i:lnw:e:' opt
do
    case $opt in
    h)
        printUsage
        ;;
    d)
        MOUNT=$(realpath $OPTARG)
        echo "Using ${MOUNT} as home directory inside docker"
        ;;
    i)
        IMAGE="$OPTARG"
        ;;
    n)
        INTERACTIVE=""
        ;;
    l)
        docker images
        exit 0
        ;;
    w)
        WORKING_DIR=$OPTARG
        ;;
    e)
        ENTRYPOINT=$OPTARG
        ;;
    *)
        printUsage
        ;;
        esac
done

if [[ -z "${IMAGE}" ]]; then
    echo "ERROR must provide an image name"
    printUsage
    exit 1
fi


MOUNT_OPTS="-v ${MOUNT}:/root/yoctohome/:rw  -v /etc/modalai/:/etc/modalai:rw -v /run/mpa/:/run/mpa:rw -v /data/:/data:rw"



# Run docker with the following options:
# --rm          automatically remove container when exiting
# -i            interactive
# -t            allocate a pseudo TTY
# -e            set environment variables within docker to match host user
# -v            mount desired directory
# -w            set working directory to home

docker run \
    --rm \
    ${INTERACTIVE} \
    --net=host \
    --privileged \
    -w ${WORKING_DIR} \
    ${MOUNT_OPTS} \
    ${IMAGE} \
    ${ENTRYPOINT}
