#!/usr/bin/env bash

# This script is used by the executor integration test to simulate Docker.
# It gets put into $PATH as "docker" and accepts the "run" command.

# Depending on the arguments to the "run" command it either acts like it
# created a tempfile, or it executes the script supplied as the last arg to
# "run".

dummy_temp_file="DUMMYDOCKER-TEMP-FILE"

workdir_prefix="/work/"

if [[ "${1}" == "run" ]]; then
    last_arg="${@: -1}"

    case "$last_arg" in
      "mktemp")
        # If the last arg is "mktemp" we're probing for a shell image and
        # want to create a temp file in the container which we can put a script.
        echo "${dummy_temp_file}"
        exit 0
        ;;

      "${dummy_temp_file}")
        # If the last arg is the temp file we "created" earlier, we now want to
        # execute it.
        #
        # We iterate over the arguments to find the things we're interested in:
        #
        # 1. The `--workdir [dir]` parameters
        # 2. The script that we need to execute
        #
        # We need (1) to execute (2) in the correct subfolder.
        # And (2) is in the matching host temp file, which should
        # be mounted into the temp file inside the container.
        #
        # We need to find it in the args and then execute it.

        workdirUpcoming=""
        workdir=""
        host_temp_file=""
        for i in "$@";
        do
          if [[ ! -z "${workdirUpcoming}" ]]; then
            workdir="${i}"
            workdirUpcoming=""
          fi
          if [[ ${i} =~ ^--workdir$ ]]; then
            workdirUpcoming="yes"
          fi

          if [[ ${i} =~ ^type=bind,source=(.*),target=${dummy_temp_file},ro$ ]]; then
            host_temp_file="${BASH_REMATCH[1]}"
          fi
        done
        [ -z "$host_temp_file" ] && echo "host temp file not found in args" && exit 1;
        [ -z "$workdir" ] && echo "workdir not found in args" && exit 1;

        # Let's strip the prefix off the workdir
        relative_workdir="${workdir#"${workdir_prefix}"}"
        if [[ "$relative_workdir" = "/work" ]]; then
          # If we couldn't strip of the prefix, it's still "/work", so we set
          # it to "".
          relative_workdir=""
        fi
        # If the non-prefixed version is not blank, then we need to `cd` into it
        if [[ ! -z "${relative_workdir}" ]]; then
          cd "${relative_workdir}"
        fi

        # Now that we have the path to the host temp file, we can execute it
        exec bash ${host_temp_file}
        ;;
      *)
        echo "dummydocker doesn't know about this command: $last_arg"
        exit 1
        ;;
    esac
fi

echo "dummydocker doesn't know about this command: $1"
exit 1
