#!/bin/bash

# Bash is needed for arrays.

LIBEXEC="$(cd "$(dirname "$0")" && pwd)"
. "${LIBEXEC}/base.sh"

# shellcheck disable=SC2034
usage=$(cat <<EOF
Run CMD in a Docker container TAG.

Usage:

  $ $(basename "$0") [-i] [-b HOSTDIR:GUESTDIR ...] TAG CMD [ARGS ...]

The special sauce is:

  1. CMD runs as you, not root or whatever is specified in the Dockerfile.
  2. Users and groups inside the container match the host.
  3. /etc/hosts is patched up to use the network effectively.

Options:

  -i  Run interactively with a pseudo-TTY
  -b  Bind-mount HOSTDIR at GUESTDIR inside the container (can be repeated)

You must have sufficient privilege (via sudo) to run the Docker commands.
EOF
)

mounts=( /etc/passwd:/etc/passwd \
         /etc/group:/etc/group )

parse_basic_args "$@"

while getopts 'b:ih' opt; do
    case $opt in
        i) interactive=-it ;;
        b) mounts+=( "$OPTARG" ) ;;
        h)
            usage 0
            ;;
        \?)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [[ $# -lt 2 ]]; then
    usage
fi

tag=$1
shift

if [[ $interactive ]]; then
    echo 'interactive mode'
fi

echo 'bind mounts:'
mount_args=''
for (( i = 0; i < ${#mounts[@]}; i++ )); do
    echo ' ' "${mounts[$i]}"
    mount_args+=" -v ${mounts[$i]}"
done

set -x
docker_ run --read-only -u "$USER" "$interactive" "$mount_args" "$tag" "$@"
