#!/bin/bash

if ! command -v podman >/dev/null 2>&1 ; then
	echo >&2 "podman not installed!"
	exit 2
fi
if ! command -v uuidgen >/dev/null 2>&1 ; then
	echo >&2 "uuidgen not installed!"
	exit 2
fi

set -e

if [[ -z "$PODMAN_IMAGE_NAME" ]]; then
	PODMAN_IMAGE_NAME=podman-gentoo-ansible-molecule
fi
podman build -q -t "$PODMAN_IMAGE_NAME" >/dev/null - <<EOF
FROM docker.io/gentoo/stage3:systemd
RUN echo "app-admin/ansible-molecule ~amd64" > /etc/portage/package.accept_keywords/ansible-molecule
RUN emerge --sync \
&& emerge -v \
app-admin/ansible-molecule \
app-admin/sudo \
app-eselect/eselect-repository \
dev-python/pexpect \
dev-python/wcmatch \
dev-vcs/git
RUN echo "%wheel ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers
RUN getuto
RUN groupadd --gid 1000 molecule
RUN useradd --create-home --uid 1000 --gid 1000 -G wheel molecule
CMD [ "/usr/sbin/init" ]
EOF

if [[ -z "$PODMAN_CONTAINER_NAME" ]]; then
	PODMAN_CONTAINER_NAME=podman-gentoo-ansible-molecule-$(uuidgen)
fi
if [[ -z "$PODMAN_WORKDIR" ]]; then
	PODMAN_WORKDIR=/workdir
fi
if ! podman ps --format "{{.Names}}" | grep -qP "^$PODMAN_CONTAINER_NAME$" ; then
	podman run --rm --detach \
	-v "$(pwd)/molecule/config.yml:/root/.config/molecule/config.yml" \
	-v "$(pwd)/molecule/config.yml:/home/molecule/.config/molecule/config.yml" \
	-v "$(pwd):/workdir:U" \
	-e "ANSIBLE_ROLES_PATH=/workdir/roles" \
	-e "ANSIBLE_COLLECTIONS_PATH=/workdir/.ansible/collections:/workdir" \
	-e "ANSIBLE_LOCAL_TEMP=/home/molecule/.ansible/tmp" \
	-e "ANSIBLE_REMOTE_TEMP=/home/molecule/.ansible/tmp" \
	--workdir "$PODMAN_WORKDIR" \
	--name "$PODMAN_CONTAINER_NAME" \
	"$PODMAN_IMAGE_NAME" >/dev/null
fi

set +e

__EXIT=0
if [[ -n "$@" ]]; then
	podman exec -it --user molecule "$PODMAN_CONTAINER_NAME" /bin/bash -c "$@"
	__EXIT=$?
else
	podman exec -it --user molecule "$PODMAN_CONTAINER_NAME" /bin/bash
	__EXIT=$?
fi

podman stop "$PODMAN_CONTAINER_NAME" >/dev/null
exit $__EXIT
