#!/bin/bash

sourced=0
if [ -n "$ZSH_EVAL_CONTEXT" ]; then
  case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$KSH_VERSION" ]; then
  [ "$(cd $(dirname -- $0) && pwd -P)/$(basename -- $0)" != "$(cd $(dirname -- ${.sh.file}) && pwd -P)/$(basename -- ${.sh.file})" ] && sourced=1
elif [ -n "$BASH_VERSION" ]; then
  (return 0 2>/dev/null) && sourced=1
else # All other shells: examine $0 for known shell binary filenames
  # Detects `sh` and `dash`; add additional shell filenames as needed.
  case ${0##*/} in sh|dash) sourced=1;; esac
fi
[[ "$sourced" = 0 ]] && echo "Error: Must source this script. Run 'source bcd <id>' instead of 'bcd <id>'" && exit

USAGE="Usage: . bcd {id substring}"

if [ $# -ne 1 ]
then
    echo "$USAGE"
    return 1
fi

dir=$(python -c "from balsam.core.models import BalsamJob;print(BalsamJob.objects.get(job_id__contains=\"$1\").working_directory)" 2>&1)

if [ $? -ne 0 ]
then
    echo "Could not match a job to ID $1"
    return 1
else
    if [ -d $dir ]
    then
        cd $dir
    else
        echo "The job directory does not exist yet: $dir"
    fi
fi
