#!/bin/bash

set -ex

ANSIBLE_TARGET_ROLE="$1"
if [[ -z "$ANSIBLE_TARGET_ROLE" ]]; then
	exit 2
fi
if [[ ! -d "roles/$ANSIBLE_TARGET_ROLE/molecule" ]]; then
	cp -r ./molecule-template "roles/$ANSIBLE_TARGET_ROLE/molecule"
	sed -i "s/MOLECULE_ROLE_NAME.*/$ANSIBLE_TARGET_ROLE/g" "roles/$ANSIBLE_TARGET_ROLE/molecule/default/converge.yml"
fi

if [[ -n "$TMUX" ]]; then
	if ! podman ps --format "{{.Names}}" | grep -Pq "^podman-gentoo-ansible-molecule-$ANSIBLE_TARGET_ROLE$" ; then
		tmux splitw -h \
		-e PODMAN_CONTAINER_NAME=podman-gentoo-ansible-molecule-$ANSIBLE_TARGET_ROLE \
		-e PODMAN_WORKDIR="/workdir/roles/$ANSIBLE_TARGET_ROLE" \
		bin/podman-gentoo-ansible-molecule
	fi

	if ! podman ps --format "{{.Names}}" | grep -Pq "^podman-debian-ansible-molecule-$ANSIBLE_TARGET_ROLE$" ; then
		tmux splitw -v \
		-e PODMAN_CONTAINER_NAME=podman-debian-ansible-molecule-$ANSIBLE_TARGET_ROLE \
		-e PODMAN_WORKDIR="/workdir/roles/$ANSIBLE_TARGET_ROLE" \
		bin/podman-debian-ansible-molecule
	fi

	tmux select-pane -L
fi
exec $EDITOR roles/$ANSIBLE_TARGET_ROLE/{defaults,tasks,meta}/main.yml roles/$ANSIBLE_TARGET_ROLE/molecule/default/*
