#!/bin/bash
################################################################################
set -eEuo pipefail

badarg() {
    echo -n "$(basename $0): " >&2
    echo "$1" >&2
    echo "Try '$(basename $0) -h' for more information." >&2
    exit 2
}

help="Usage: $(basename $0) [-h] container [command]
Runs a bash shell on the given container.

If the second argument is omitted, an interactive login shell is launched. If the
second argument is present, the string is interpreted as a command and executed
directly. To ensure that any shell syntax is evaluated in the container shell
instead of the host shell, make sure to wrap your string in single quotes.

Options:
  -h    Display this help and exit"

# Handle options
while getopts ':h' arg; do
    case $arg in
        h) echo "$help"; exit 0;;
        :) badarg "Argument missing for option '-$OPTARG'";;
        ?) badarg "Invalid option '-$OPTARG'";;
    esac
done
shift $((OPTIND -1))

# Handle non-option arguments
if [[ $# -lt 1 ]]; then
    badarg "Missing container name"
else
    container="$1"
fi

if [[ $# -gt 2 ]]; then
        badarg "Too many arguments"
fi

# Main
if [[ $# -eq 1 ]]; then
        podman exec -it "$container" bash -l
else
        podman exec -it "$container" bash -c "${@:2}"
fi