#!/bin/bash

#set -x

function usage()
{
   local fusage="$1"

   if [[ -n "$fusage" ]]; then
      fwdline1="[-dlw]"
      fwdline2="Create a container based off the \"${fwddocker_image}\" Docker image"
      fwdline3=""
   else
      fwdline1="[-dlwf]"
      fwdline2="Create a container based off the \"${docker_image}\" Docker image"
      fwdline3="-f = Include FWD in the container. Specify a tag with --tag=<tag>, if desired. (default=${tag})."
   fi

   cat <<EOF
Usage: $0 ${fwdline1} [-v <volume>] [--port-gui] [--port-debug] [--port-jmx] [--port-pg=<port>] \
[--tag=<tag>] [--name=<name>] \
[--pg<14|15|16|17>] \
[--pgport=<port>] \
[--host] \
[--manual_port=<hport:cport>[,<hport:cport>...]] \
[--manual_mount=<ext_vol:int_vol>[,<ext_vol:int_vol>...]] \
[--startup_hook=<startup_file>] \
[--jdk<21|25>] \
[--detach] \
[--app=<appdir>] \
[--fwd_lib=<fwd_lib>] \
[-c <cmd_line>]

${fwdline2}

Where:
       -d = dryrun (just display commands)
       -l = local image. Don't use goldencode/ repository.
       -w = Use fwd account instead of mapping in ${USER} account.
EOF
   [[ -n "$fwdline3" ]] && echo "       $fwdline3"
   cat <<EOF
       -v = Volume for database to mount to /opt/db (if PostgreSQL included).
       --port-gui = Open typical GUI ports (7443 and 7449-7459)
       --port-debug = Open typical debug ports (2080 and 5000)
       --port-jmx = Open JMX 22100 port
       --port-pg=<port> = Open <port> (usually 5432) to the PGPORT (override container port ${pgport_val} with --pgport=<port>)
       --tag=<tag> = Use given tag for FWD included in the image (default=${tag}).
       --name=<name> = Use <name> as the container name and hostname, instead of the generated one. It fails if a container with that name already exists.
       --pg<14|15|16|17> = Include given PostgreSQL in the container. The default is no PostgreSQL.
       --pgport=<port> Use this port for PostgreSQL. The default is ${pgport_val}. It will export PGPORT=<port>.
       --pgdata=<pgdata> Startup PostgreSQL using this cluster. It will export PGDATA=/opt/db/<pgdata>
       --host = Use host's network.
       --manual_port=<hport:cport>[,<hport:cport>...] include one or more port openings with "-p hport:cport".
       --manual_mount=<ext_vol:int_vol>[,<ext_vol:int_vol>...] include one or more mountpoints with "-v ext_vol:int_vol"
       --startup_hook=<startup_file> the base_entrypoint.sh will hook <startup_file> for an installation instead of the default \"$hook_default\""
       --jdk<21|25> = Use given JDK as the default for the container. The default is JDK${jdk_version}.
       --app=<appdir> = Set /opt/app directory in container to give <appdir> directory on host, typically the deploy directory.
       --fwd_lib=<fwd_lib> = Set FWD_LIB environment variable to <fwd_lib> path. This allows scripts to find FWD.
       --detach = Run the container detached. Use "docker attach ..." to attach and "CTRL-p CTRL-q" to detach again.
       -c <cmd_line> = Pass a command line to the Docker container.

 -? or -h or --help = show usage.
EOF
}

# Function to determine the next available container name,
# if the given container name is already taken
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 container of the initial name
      if [ $i -gt 0 ]; then
         candidate_name="${base_name}${i}"
      fi

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

   echo "0"
}

get_longopt_value()
{
   local opt_name="$1"
   local optarg="$2"
   local value

   if [[ "$optarg" != "${opt_name}="* ]]; then
      echo "ERROR: --${opt_name} requires a value." >&2
      return 1
   fi

   value="${optarg#*=}"
   if [[ -z "$value" ]]; then
      echo "ERROR: --${opt_name} requires a non-empty value." >&2
      return 1
   fi

   printf '%s' "$value"
}

csv_to_docker_args()
{
   local opt_name="$1"
   local docker_flag="$2"
   local values="$3"
   local -n out_args_ref=$4
   local item

   IFS=',' read -r -a entries <<< "$values"

   for item in "${entries[@]}"; do
      # Trim whitespace around each comma-separated item.
      item="${item#"${item%%[![:space:]]*}"}"
      item="${item%"${item##*[![:space:]]}"}"

      if [[ -z "$item" ]]; then
         echo "ERROR: ${opt_name} contains an empty list item: $values" >&2
         return 1
      fi

      if [[ "$item" != *:* ]]; then
         echo "ERROR: ${opt_name} item must contain ':': $item" >&2
         return 1
      fi

      out_args_ref+=( "$docker_flag" "$item" )
   done
}

# Defaults
jdk_version="17"
tag="latest"
repo="goldencode/"
pull="always"
gui_ports=()
jmx_port=()
pgport_val="5432"
portpg_open=""
debug_ports=()
docker_image="basedev_ubuntu_24.04"
fwddocker_image="fwddev_4.0_ubuntu_24.04"
hook_default="./docker/startup_hook.sh"
run_detached=""
mount_args=()
env_args=()
port_args=()
manual_port_args=()
manual_mount_args=()

while getopts ":h?dlwv:c:-:f" opt; do
   case $opt in
      d  ) mycmd="echo"
           ;;
      l  ) unset repo
	   pull="never"
           ;;
      w  ) use_fwd_id=true
           ;;
      v  ) vol="${OPTARG}"
           ;;
      c  ) cmd_line="${OPTARG}"
           ;;
      f  ) fwd="_fwd"
           fwd_flag=true
           ;;
      -  ) case ${OPTARG} in
             "port-gui"      ) gui_ports=( -p "7443:7443" -p "7449-7459:7449-7459" ) ;;
             "port-debug"    ) debug_ports=( -p "2080:2080" -p "5000:5000" ) ;;
             "port-jmx"      ) jmx_port=( -p "22100:22100" ) ;;
             "port-pg="*     ) portpg_open=$(echo $OPTARG | cut -d"=" -f2) ;;
             "tag="*         ) tag=$(echo $OPTARG | cut -d"=" -f2) ;;
             "name="*        ) explicit_name=$(get_longopt_value "name" "$OPTARG") || { usage; exit 1; } ;;
             "manual_port="* ) value=$(get_longopt_value "manual_port" "$OPTARG") || { usage; exit 1; }
                               csv_to_docker_args "--manual_port" "-p" "$value" manual_port_args || { usage; exit 1; } ;;
             "manual_mount="*) value=$(get_longopt_value "manual_mount" "$OPTARG") || { usage; exit 1; }
                               csv_to_docker_args "--manual_mount" "-v" "$value" manual_mount_args || { usage; exit 1; } ;;
             "startup_hook"* ) hook_file=$(echo $OPTARG | cut -d"=" -f2) ;;
             "pg1"*          ) pg_version="${OPTARG}"
                               pg_flag=true ;;
             "pgport="*      ) pgport_val=$(echo $OPTARG | cut -d"=" -f2) ;;
             "pgdata="*      ) pgdata_val=$(echo $OPTARG | cut -d"=" -f2) ;;
             "host"          ) host_network="--network host" ;;
             "jdk"*          ) jdk_version="${OPTARG}" ;;
             "app="*         ) appdir=$(echo $OPTARG | cut -d"=" -f2) ;;
             "fwd_lib="*     ) fwd_lib=$(echo $OPTARG | cut -d"=" -f2) ;;
             "detach"        ) run_detached="--detach" ;;
             "help"  ) usage
                       exit 0 ;;
             "fhelp" ) usage -f
                       exit 0 ;;
              *      ) echo "Unknown option: --${OPTARG}"
                       usage
                       exit 1 ;;
           esac
           ;;
      h | \? ) if [[ "$OPTARG" == "?" || "$opt" == "h" ]]; then
                  usage
                  exit 1
               else
                  echo "Unknown option: -${OPTARG}"
                  usage
                  exit 1
               fi
               ;;
   esac
done
shift $(($OPTIND - 1))

# Check on PostgreSQL
if [[ "$pg_flag" == true ]]; then
   if [[ $pg_version =~ ^pg([0-9]+)$ ]]; then
       numver="${BASH_REMATCH[1]}"
   else
       echo "ERROR: Invalid format '$pg_version' (expected 'pgXX' or 'XX')" >&2
       exit 1
   fi
   # Verify valid versions
   case "$numver" in
    14|15|16|17)
        pg="_pg${numver}"
        ;;
    *)
        echo "ERROR: Unsupported PostgreSQL version '$numver' (valid: 14, 15, 16, 17)" >&2
        exit 1
        ;;
   esac
   if [ -z "$vol" ]; then
     echo "ERROR: No volume passed for database." >&2
     usage
     exit 1
   else
      mount_args+=( -v "$vol:/opt/db" )
   fi
   # Setup PGPORT for container's usage
   env_args+=( -e "PGPORT=${pgport_val}" )
   # Setup PG ports, if specified to be open
   [[ -n "$portpg_open" ]] && port_args+=( -p "${portpg_open}:${pgport_val}" )
   # Setup PGDATA if the cluster is to be started
   [[ -n "$pgdata_val" ]] && env_args+=( -e "PGDATA=/opt/db/${pgdata_val}" )
fi

# Check on Java
if [[ $jdk_version =~ ^jdk([0-9]+)$ ]]; then
   numver="${BASH_REMATCH[1]}"
elif [[ $jdk_version =~ ^[0-9]+$ ]]; then
   numver=$jdk_version
else
   echo "ERROR: Invalid format '$jdk_version' (expected 'jdkXX' or 'XX')" >&2
   exit 1
fi
env_args+=( -e "JDK_VERSION=${numver}" )
jdk="_jdk${numver:-17}"

# Build Docker image name based on fwd, pg, and jdk
[ "$fwd_flag" = true ] && docker_image=${fwddocker_image}${pg}${jdk} || docker_image+=${pg}

max_containers=10  # Maximum of the same container we allow concurrently
container_name=${docker_image}_${tag}_container
container_name="${container_name//[^[:alnum:]_-]/}"

(( ${#gui_ports[@]} > 0 )) && port_args+=( "${gui_ports[@]}" )
(( ${#debug_ports[@]} > 0 )) && port_args+=( "${debug_ports[@]}" )
(( ${#jmx_port[@]} > 0 )) && port_args+=( "${jmx_port[@]}" )
(( ${#manual_port_args[@]} > 0 )) && port_args+=( "${manual_port_args[@]}" )
if [ -n "$explicit_name" ]; then
   # An explicit name is used as given; it is never bumped with a numeric suffix.
   if [[ ! "$explicit_name" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]*$ ]]; then
      echo "ERROR: Invalid --name '${explicit_name}' (use letters, digits, '_', '.' and '-', starting with a letter or digit)." >&2
      exit 1
   fi
   if [ -n "$(docker ps -aq -f name=^/${explicit_name}$)" ]; then
      echo "ERROR: A container named ${explicit_name} already exists. Remove it with \"docker rm -f ${explicit_name}\" or pick another --name." >&2
      exit 1
   fi
   container_name="$explicit_name"
else
   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
fi

if [[ "$use_fwd_id" = true ]]; then
   mount_args+=( -v "${HOME}:/home/fwd" )
   env_args+=( -e "HOST_UID=1000" -e "HOST_GID=1000" -e "HOME=/home/fwd" -e "USER=fwd" )
   working_dir="/home/fwd"
   user="fwd"
else
   host_pwd="$(pwd -P)"
   mount_args+=( -v "${HOME}:/home/${USER}" )
   mount_args+=( -v "/etc/passwd:/etc/passwd:ro" )
   mount_args+=( -v "/etc/group:/etc/group:ro" )
   mount_args+=( -v "/etc/shadow:/etc/shadow:ro" )
   mount_args+=( -v "/etc/sudoers:/etc/sudoers:ro" )
   env_args+=( -e "HOST_UID=$(id -u)" )
   env_args+=( -e "HOST_GID=$(id -g)" )
   env_args+=( -e "HOME=${HOME}" )
   env_args+=( -e "USER=${USER}" )
   working_dir="$host_pwd"
   user=$USER
   [[ "$fwd_flag" = true ]] && user_override=( --user "root" ) || true
fi
(( ${#manual_mount_args[@]} > 0 )) && mount_args+=( "${manual_mount_args[@]}" )

# Check on appdir passed in
[ -n "$appdir" ] && mount_args+=( -v "${appdir}:/opt/app" )

# Check on fwd_lib passed in
[ -n "$fwd_lib" ] && env_args+=( -e "FWD_LIB=${fwd_lib}" )

# Check on startup hook
[ -z "$hook_file" ] && hook_file=$hook_default
[ -f "$hook_file" ] && mount_args+=( -v "${hook_file}:/docker_install_hook.sh:ro" )

# Complete docker run command array
docker_cmd=( docker run )

[[ -n "$run_detached" ]] && docker_cmd+=( "$run_detached" )
docker_cmd+=( -e "DBASH=true" )

[[ -n "$host_network" ]] && docker_cmd+=( --network host )

docker_cmd+=( --name "$container_name" -h "$container_name" )

(( ${#user_override[@]} > 0 )) && docker_cmd+=( "${user_override[@]}" )

[[ -z "$run_detached" ]] && docker_cmd+=( --rm )
docker_cmd+=( -it )

(( ${#port_args[@]} > 0 )) && docker_cmd+=( "${port_args[@]}" )

(( ${#mount_args[@]} > 0 )) && docker_cmd+=( "${mount_args[@]}" )

docker_cmd+=( --pull "$pull" )

(( ${#env_args[@]} > 0 )) && docker_cmd+=( "${env_args[@]}" )

docker_cmd+=( -w "$working_dir" )

docker_cmd+=( "${repo}${docker_image}:${tag}" )
docker_cmd+=( "$user" -- )

if [[ -n "$cmd_line" ]]; then
   docker_cmd+=( bash -lc "$cmd_line" )
else
   docker_cmd+=( bash )
fi

printf 'Running: '
printf '%q ' "${docker_cmd[@]}"
echo

if [[ "$mycmd" == "echo" ]]; then
   :
else
   "${docker_cmd[@]}"
fi

exit 0
