#!/bin/sh

base_path="~/projects/system/dev-env/scripts/"
mount_path=$(pwd)
if [[ -n "$2" ]]; then
	name=$2
else
	name=$(pwd | rev | cut -d "/" -f 1-2 | rev | sed -e 's/\//-/')
fi

if [[ $1 == "help" ]]; then
	echo "
dev-containers [container|rm|help] [name]

Container can be one of:
    - base
    - node
    - php
    - python
    - torch-rocm
    - vue
    - webserver
rm removes the container for the current directory if provided name is existing container, or unspecified.
    "
	exit 0
fi

echo "
    janishutz dev containers
"
if [[ $(systemctl is-active docker) != "active" ]]; then
	echo "
 -> Docker daemon not running, starting with systemctl <-
    "
	sudo systemctl start docker
fi

if [[ $1 == "rm" ]]; then
	echo "
    -> Removing containers with $name in their name <-
"
    if [[ $(read -p "Do you really want to delete ALL containers for this directory? (y/N) " response && echo $response) == 'y' ]]; then
		for container in $(docker container ls -aq -f name=$name); do
			docker stop $container
			docker container rm $container
		done
    else
        echo "Aborting."
        exit 0
	fi
elif [[ $1 == "shell" ]]; then
    containers=$(docker ps -q -f name=$name)
    count=$((${#containers[@]}))
    
    if [[ ${containers[0]} == "" ]]; then
        count=$(($count-1))
    fi

    if [[ $count == 0 ]]; then
        echo "
    -> No suitable running container found. Aborting.
        "
    elif [[ $count == 1 ]]; then
        echo "
    -> Connecting to running container ${containers[0]}
"
        docker exec -it ${containers[0]} '/bin/bash'
    else
        echo "
    -> Multiple possible containers found to attach to. Pick one (enter number)
        "
        docker ps -f name=$name
        read -p "Enter number (1-$(${#containers[@]})) " sel
        docker exec -it containers[$sel] '/bin/bash'
    fi
else
	name=$name-$1
	if [[ $(docker container ls -aq -f name=$name) != "" ]]; then
		echo "
    -> Starting existing container $name <-
"
		docker start -i $name
	else
		echo "
    -> Creating container $name <-
"
		eval "${base_path}$1-container $name $mount_path"
	fi
fi
