#!/usr/bin/bash
set -o errexit -o pipefail -o nounset

print_possible_containers() {
  podman ps --all --format '{{.Names}} {{.Command}}' | awk '$2 == "sleep" { print $1 }'
}

if [[ -v CNEST_COMPLETION ]]; then
  print_possible_containers
  exit 0
fi

if [[ $# -lt 1 ]]; then
  THIS_SCRIPT=$'\u001b[1m'$(basename "$0")$'\u001b[0m'
  printf "Usage:\n  [USER=user] $THIS_SCRIPT container [command]\n\n"
  CONTAINERS=$(print_possible_containers)
  if [[ -n $CONTAINERS ]]; then
    printf "Possible containers:\n  ${CONTAINERS//$'\n'/$'\n'  }\n"
  fi
  exit 2
fi

CONTAINER="$1"
shift
COMMAND="$@"
if [[ -z $COMMAND ]]; then
  COMMAND="/bin/bash --login"
fi

if [[ ! -v USER ]]; then
  USER=$(id -un)
fi

podman start $CONTAINER

WORKDIR="/home/$USER"

# Determine whether current dir is same inside container
SUBCMD="stat --printf=%d:%i \"\$(realpath \"$PWD\")\""
if NEST_DEV_INODE=$(podman exec $CONTAINER bash -c "$SUBCMD" 2>/dev/null); then
  HOST_DEV_INODE=$(stat --printf=%d:%i "$(realpath "$PWD")")
  if [[ "$NEST_DEV_INODE" == "$HOST_DEV_INODE" ]]; then
    WORKDIR=$PWD
  else
    echo \'$PWD\' is a different directory in the container
  fi
else
  echo \'$PWD\' does not exist in the container
fi

set +o errexit

podman exec -it \
  -e LANG \
  -e TERM \
  -e DISPLAY \
  -e CONTAINER_NAME=$CONTAINER \
  --detach-keys="" \
  --user $USER \
  --workdir "$WORKDIR" \
  $CONTAINER \
  $COMMAND

STATUS=$?

NUM_EXEC=$(podman container inspect --format "{{len .ExecIDs}}" $CONTAINER)
if [[ $NUM_EXEC -eq 0 ]]; then
  podman stop $CONTAINER
fi

exit $STATUS
