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

print_local_images() {
  podman images --format '{{.Repository}}:{{.Tag}}'
}

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

print_usage() {
  COMMAND=$'\u001b[1m'$(basename "$0")$'\u001b[0m'
  printf "Usage:\n  [USER=user] $COMMAND image [podman_create_options ...]\n\n"
  IMAGES=$(print_local_images)
  if [[ -n $IMAGES ]]; then
    printf "Locally stored images:\n  ${IMAGES//$'\n'/$'\n'  }\n"
  fi
  exit 2
}

if [[ $# -lt 1 ]]; then
  print_usage
fi

IMAGE=$1
shift
if [[ $IMAGE == -* ]]; then
  printf "Bad input:
  An image reference should be the first argument, not option '$IMAGE'\n\n"
  print_usage
fi

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

CUID=48222 # UID/GID in container for host user
CIDFILE=$(mktemp)
(set -o xtrace
 podman run \
    --detach \
    --cidfile=$CIDFILE \
    --userns=keep-id:uid=$CUID,gid=$CUID \
    --init \
    --user=root \
    "$@" \
    $IMAGE \
    sleep inf)
CONTAINER_ID=$(< $CIDFILE)

podman inspect $CONTAINER_ID --format={{.Name}}

exit_status=0

{ podman exec -i --user root $CONTAINER_ID \
  bash -s $USER $CUID <<'EOF'
    set -o nounset
    groupadd --gid $2 $1
    useradd --uid $2 --gid $2 --no-create-home --comment $1 --password '' $1
    mkdir --parents /home/$1
    chown $1: /home/$1
    chmod 755 /home/$1
EOF
} || exit_status=1

{ podman exec --user $USER $CONTAINER_ID \
  cp --recursive --preserve --no-clobber /etc/skel/. /home/$USER
} || true  # ignore unreliable no-clobber exit status

{ podman exec -i --user root $CONTAINER_ID \
  cp --no-preserve=all /dev/stdin /etc/profile.d/nestprompt.sh <<'EOF'
    if [ -n "$PS1" ] && [ -r /etc/nestsign ]; then
        NESTSIGN=$(cat /etc/nestsign)
        case "$PS1" in
            '\s-\v\$ ') # default bash prompt
                PS1="$NESTSIGN$CONTAINER_NAME[\u@\h \W]\\$ " ;;
            *debian_chroot*)
                debian_chroot=$NESTSIGN$CONTAINER_NAME ;;
            [*)
                PS1="$NESTSIGN$CONTAINER_NAME$PS1" ;;
        esac
    fi
EOF
} || exit_status=1

{ podman exec -i --user root $CONTAINER_ID \
  bash <<'EOF'
    [ -f /etc/nestsign ] || echo 📦 > /etc/nestsign
EOF
} || exit_status=1

podman stop $CONTAINER_ID > /dev/null || exit_status=1

exit $exit_status
