#!/bin/sh
# Run a program that will create CCCma job strings
# Use the --help option to get on line documentation
#
# L.P. Solheim  created Jan 17,2006

set -a

# simple error exit routine
INVOKED_NAME=`basename $0`
bail(){
  echo "${INVOKED_NAME}: $1"
  exit 1
}

# CCRNSRC must be defined
CCRNSRC=${CCRNSRC:=/home/acrnsrc}
[   -z "$CCRNSRC" ] && bail "CCRNSRC must be defined"
[ ! -d "$CCRNSRC" ] && bail "$CCRNSRC is not a directory"

# Define a default path to the root of the cccjob directory tree
this_host=`hostname`
case $this_host in
#  xc1*|xc2*) # Assume cccjob_dir contains a working copy of the CanCPL git repo
#             # This should contain a bin dir at the top level rather than pub/bin
#             DEF_ROOT=$CCRNSRC/cccjob_dir ;;
          *) # This is the leagacy default
             DEF_ROOT=$CCRNSRC/cccjob_dir/pub ;;
esac

# If the user has supplied a git commit id (usually a tag) then use it to
# create a tmp dir containing the cccjob dir tree from a known git mirror
# Allow a user defined CCCJOB_ROOT to override CCCJOB_VERSION
if [ -n "$CCCJOB_VERSION" -a -z "$CCCJOB_ROOT" ]; then
  # This is the default location for the mirror on all machines
  GIT_MIRROR=$CCRNSRC/cccjob_dir/cccjob.git
  [ -d "$GIT_MIRROR" ] || bail "$GIT_MIRROR is not a directory"
fi

# Allow user override via the environment variable CCCJOB_ROOT
if [ -s $HOME/cccjobs/.cccjobrc ]; then
  if [ -z "$CCCJOB_ROOT" ]; then
    # If the cccjob startup file exists and the user has not defined
    # CCCJOB_ROOT from the command line then set it from the startup
    # file, if it is defined there
    . $HOME/cccjobs/.cccjobrc || :
  fi
fi
CCCJOB_ROOT=${CCCJOB_ROOT:=$DEF_ROOT}
[ ! -d "$CCCJOB_ROOT" ] && bail "$CCCJOB_ROOT is not a directory"

# The driver should be in a standard location below CCCJOB_ROOT
EXEC_PATH=$CCCJOB_ROOT/bin/cccjob_driver

# make sure the file exists and is executable
[ ! -s "$EXEC_PATH" ] && bail "driver $EXEC_PATH is missing"
[ ! -x "$EXEC_PATH" ] && bail "${EXEC_PATH}: permission denied"

# run the program
exec $EXEC_PATH "$@"
