#!/bin/bash

# Make sure at least kill and grep are in path on various systems
PATH=$PATH:/bin:/usr/bin

# set up the environment that was saved by sshd_setup
if [ "$1" != "" ]; then
  . "$1"
fi

# go to the job's working directory
for dir in "${_CONDOR_JOB_IWD}" "${_CONDOR_SCRATCH_DIR}"; do
  if cd "${dir}"; then
    break
  fi
done

# kill the dummy sleep job if this is an interactive job
if grep -q '^InteractiveJob = true' "${_CONDOR_SCRATCH_DIR}/.job.ad"; then
  if [ "${_CONDOR_JOB_PIDS}" != "" ]; then
	if [ ! -S ${_CONDOR_SCRATCH_DIR}/.docker_sock ]; then
    		kill "${_CONDOR_JOB_PIDS}" 2>/dev/null
		_CONDOR_JOB_PIDS=""
	fi
  fi
fi


if [ "${SSH_ORIGINAL_COMMAND}" != "" ]; then
  # run the command specified by the user
  eval ${SSH_ORIGINAL_COMMAND}
else
  if [ "${_CONDOR_SLOT_NAME}" != "" ]; then
    echo "Welcome to ${_CONDOR_SLOT_NAME}"'!'
  fi
  if [ "${_CONDOR_JOB_PIDS}" != "" ]; then
    echo "Your condor job is running with pid(s) ${_CONDOR_JOB_PIDS}."
  fi
  if [ "${TMOUT}" != "" ]; then
    echo "You will be logged out after ${TMOUT} seconds of inactivity."
  fi


  if [ -S ${_CONDOR_SCRATCH_DIR}/.docker_sock ]
  then
	CONDOR_CONFIG=/dev/null
	export CONDOR_CONFIG
	
	cd $_CONDOR_SCRATCH_DIR
	exec "$_CONDOR_BIN"/condor_docker_enter
  fi
  # start a shell for the user
  if [ "${_CONDOR_SHELL}" != "" ]; then
    # use the shell preferred by the user
    exec -l "${_CONDOR_SHELL}"
  fi
  exec -l "${SHELL}"
fi
