#!/usr/bin/env sh
#
# ---
# source: https://github.com/Jorenar/dotfiles

set -e

if command -v podman >/dev/null 2>&1; then
  >&2 echo "$(basename "$0"):" "error:" "podman not found"
  exit 1
fi

img="$1"
shift
ref="${img##*/}"
ref="${ref%:*}"

esceval() {
  printf '%s\n' "$1" | sed "s/'/'\\\\''/g; 1 s/^/'/; $ s/$/'/"
}

entrypoint="sh"

if [ "$#" -eq 0 ]; then
  set -- '-li'
elif [ "$1" = "--" ]; then
  entrypoint="$2"
  shift 2
else
  cmd=
  for a in "$@"; do
    cmd="${cmd} $(esceval "$a")"
  done
  set -- '-l' '-c' '--' "$cmd"
fi

# shellcheck disable=SC2312
exec podman run --interactive --tty --rm \
  --net host --privileged --user \
  --hostname "${ref}.$(hostname -s)" \
  --env HOME --volume "${HOME}:${HOME}" \
  --volume "/etc/localtime:/etc/localtime:ro" \
  --env DISPLAY --volume "/tmp/.X11-unix/:/tmp/.X11-unix/" \
  --volume "/:/mnt/host" \
  --volume "${PWD}:${PWD}" --workdir "${PWD}" \
  --entrypoint "${entrypoint}" \
  "${img}" \
  "$@"
