#!/bin/bash set -euo pipefail REGISTRY="registry.tomastm.com" usage() { echo "Usage: $0 -i " exit 1 } # Parse arguments while getopts ":i:" opt; do case ${opt} in i ) IFS=':' read -r IMAGE IMAGE_TAG <<< "${OPTARG}" # Split image and tag IMAGE_TAG=${IMAGE_TAG:-latest} # Default to 'latest' if no tag is provided FULL_IMAGE_NAME="${REGISTRY}/${OPTARG}" # Keep the full image name with tag ;; \? ) usage ;; esac done shift "$((OPTIND -1))" if [ -z "$FULL_IMAGE_NAME" ] || [ -z "$1" ]; then usage fi NAME="$1" CONTAINER_NAME="${IMAGE##*/}-${NAME}" # Use only the base image name (without tag) exec_into_container() { docker exec --detach-keys "ctrl-q,ctrl-p" -it "$CONTAINER_NAME" bash -c "zsh" } # Check if the container exists if [ "$(docker ps -a -q -f "name=$CONTAINER_NAME")" ]; then # Container exists, start it if it's not running if [ ! "$(docker ps -q -f "name=$CONTAINER_NAME")" ]; then echo "Container $CONTAINER_NAME exists but is not running. Starting it..." docker start "$CONTAINER_NAME" else echo "Container $CONTAINER_NAME is already running." fi else echo "Container $CONTAINER_NAME does not exist. Creating and running it in detached mode..." docker run -d \ --network host \ -v "$HOME/.ssh:/home/dev/.ssh" \ -v "$PWD:/workspace" \ -v /var/run/docker.sock:/var/run/docker.sock \ --group-add "$(getent group docker | cut -d: -f3)" \ --name "$CONTAINER_NAME" \ --init \ # run tini as PID 1 to handle signals & reap zombies for cleaner container shutdown "$FULL_IMAGE_NAME" \ sleep infinity # use if coreutils not available: tail -f /dev/null fi echo "Executing into container $CONTAINER_NAME..." exec_into_container