#!/bin/bash

#set -x

function usage()
{
   i=0;       usage[$i]="Usage: $0 [-d] [--jdk8] [-c <cmd_line>] [-f [branch]]"
   i=$((i+1));usage[$i]="\nCreate a container from the base_ubuntu_22.04 or fwd_4.0_ubuntu_22.04 Docker image"
   i=$((i+1));usage[$i]="\nWhere:"
   i=$((i+1));usage[$i]="\t-d = dryrun (just display commands)"
   i=$((i+1));usage[$i]="\t--jdk8 = Include JDK8 in the container. The default is JDK17."
   i=$((i+1));usage[$i]="\t-c <cmd_line> = Pass a command line to the Docker container."
   i=$((i+1));usage[$i]="\t-f [tag] = Include FWD in the container. Specify a tag, if desired. (default=trunk_latest). *MUST be last parameter*"
   i=$((i+1));usage[$i]="\n -? or -h or --help = show usage."

   for i in "${usage[@]}"; do
      echo -e $i
   done
}

# Function to determine the next available container name,
# if the given container is already running
get_container()
{
   local base_name=$1
   local max=$2
   local candidate_name="$base_name"
   local cid

   for ((i = 0; i < max; i++)); do
      # Only bump the name if there is a running container of the initial name
      if [ $i -gt 0 ]; then
         candidate_name="${base_name}${i}"
      fi

      cid=$(docker ps -q -f status=running -f name=^/${candidate_name}$)
      if [ -z "$cid" ]; then
         echo "$candidate_name"
         return
      fi
   done

   echo "0"
}

# This has limited potential. It has 2 limits:
# 1) We can only have 1 argument with options
# 2) It must be at the end of the list of arguments
# Other than that, it works great.
getopts_get_optional_argument()
{
  next_token="${!OPTIND}"
  #${parameter:offset:length}
  if [[ "${next_token:0:1}" = "-" ]]; then
     next_token=${next_token:2}
  fi
  if [[ -n $next_token && $next_token != -* ]]; then
    OPTIND=$((OPTIND + 1))
    OPTARG=$next_token
  else
    unset OPTARG
  fi
}

# Defaults
jdk_version="jdk17"
docker_image="goldencode/base_ubuntu_22.04"
tag="trunk_latest"

while getopts ":h?dc:-:f" opt; do
   case $opt in
      d  ) mycmd="echo"
           ;;
      c  ) cmd_line="${OPTARG}"
           ;;
      -  ) case ${OPTARG} in
             "jdk8" ) jdk_version="jdk8" ;;
             "help" ) usage
                      exit 1 ;;
              * ) echo "Unknown option: --${OPTARG}"
                  usage
                  exit 1 ;;
           esac
           ;;
      f  ) getopts_get_optional_argument "$@"
           [ ! -z "${OPTARG}" ] && tag="${OPTARG}"
           docker_image="goldencode/fwd_4.0_ubuntu_22.04"
           fwd="_fwd"
           ;;
      h | \? ) if [[ "$OPTARG" == "?" || "$opt" == "h" ]]; then
                  usage
                  exit 1
               else
                  echo "Unknown option: -${OPTARG}"
                  usage
                  exit 1
               fi
               ;;
   esac
done
shift $(($OPTIND - 1))

max_containers=10  # Maximum builds we allow concurrently
container_name="${jdk_version}${fwd}_container_${tag}"
[ "$jdk_version" != "jdk8" ] && docker_image+="_${jdk_version}"

check_container_name=$(get_container $container_name $max_containers)
if [ "$check_container_name" == "0" ]; then
   echo "ERROR: Too many ${container_name} containers (max=${max_containers}) running. "
   exit
else
   container_name=$check_container_name
fi

if [ -z "$cmd_line" ]; then
   cmd_line="bash"
else
   cmd_line="sh -c \"${cmd_line}\""
fi

volumes="-v ${HOME}:/home/${USER} -v /etc/passwd:/etc/passwd:ro -v /etc/group:/etc/group:ro"
dcmd="$mycmd docker run --name $container_name -h $container_name --rm -it $volumes --pull always -u $(id -u):$(id -g) -e HOME=${HOME} -e USER=${USER} -w $(pwd) ${docker_image}:${tag} $cmd_line"
echo "Running: $dcmd"
eval $dcmd

