#! /bin/bash
#
# run jmc command in a container, with some extensions
#
# env:
# - POD: container command, either "docker" or "podman"
# - JMC: jmc container tag to run
# - JMC_ENV: names of environment variables to export
# - WORKDIR: working directory to use

pod=${POD:-docker}

# SELinux permission issue
workspace="/app/workspace"
[ "$pod" = "podman" ] && workspace+=":z"

container_image="docker.io/zx80/jmc:${JMC:-latest}"
container_root=($pod run --name acme_jmc_$$ -v "${WORKDIR:-.}:$workspace" --rm)

# export environment variables to container
for var in $JMC_ENV ; do
  if [ "${!var}" ] ; then
    container_root+=(-e "$var=${!var}")
  else
    echo "### skipping empty or non existing environment variable $var" >&2
  fi
done

if [ "$pod" = "docker" ] ; then
  container_root+=(--hostname=$(hostname))
elif [ "$pod" = "podman" ] ; then
  # container_root+=(-e HOSTNAME=$(hostname))
  container_root+=(--uts=private --hostname=$(hostname))
else
  echo "unexpected container command: $pod" >&2
  exit 1
fi

container_user=("${container_root[@]}")
if [ "$pod" = "docker" ] ; then
  container_user+=(--user "$(id -u):$(id -g)")
  if [ -f /etc/passwd ] ; then
    container_user+=(-v /etc/passwd:/etc/passwd:ro -v /etc/group:/etc/group:ro)
  fi
fi

if [ "$#" -ge 1 -a "$1" = "help" ] ; then
  echo "$0 [ help | run | exec | shell | root ] …"
elif [ "$#" -ge 1 -a "$1" = "shell" ] ; then
  shift 1
  exec "${container_user[@]}" -it --entrypoint /bin/bash "$container_image" "$@"
elif [ "$#" -ge 1 -a "$1" = "root" ] ; then
  shift 1
  exec "${container_root[@]}" -it --entrypoint /bin/bash "$container_image" "$@"
elif [ "$#" -ge 1 -a "$1" = "exec" ] ; then
  exe=$2
  shift 2
  exec "${container_user[@]}" --entrypoint "$exe" "$container_image" "$@"
elif [ "$#" -ge 1 -a "$1" = "run" ] ; then
  shift 1
  exec "${container_user[@]}" "$container_image" "$@"
else
  exec "${container_user[@]}" "$container_image" "$@"
fi
