#!/bin/bash

# Building a Docker image in which to execute tests
# will require a copy of the local Capo properties
# file, which can be found at /home/casa/capo
# on boxes that can see /home, but which on boxes
# that can't is likely to be at ~/home/.capo for
# any given user. Find local.properties and
# copy it to our test directory. Dockerfiles
# do not support conditional logic; hence this script.

# Execute script from apps/executables/cli/datafetcher/

FILENAME=local.properties
CONTAINER_NAME=$1;shift
CACHE_FLAG=$1;shift
USAGE='Usage: $0 <container_name> [--NO-CACHE]'
if [[ -z "${CONTAINER_NAME}" ]]
then
  echo "${USAGE}"
  exit 1
fi

if [ -z "${CACHE_FLAG}" ]
then
  shopt -s nocasematch
  if [[ "${CACHE_FLAG}" =~ ^NO[-_]CACHE$ ]]
  then
    echo 'invalid cache flag: '"${CACHE_FLAG}"
    exit 1
  else
    USE_CACHE=1
  fi
else
  USE_CACHE=0
fi

# conda will need the environment.yml
export ENV_YML=environment.yml
export YML_DIR=../../../../
cp $YML_DIR${ENV_YML} ${ENV_YML}

# The preferred version of Capo .properties files is always
# the one at /home/casa/capo, -if- this is visible
# (i.e., NRAO internal system). If not (i.e., developer laptop),
# get the one in the user's .capo directory
if [ -e /home/casa/capo/${FILENAME} ]
then
    SOURCE=/home/casa/capo/${FILENAME}
elif [ -e ~/.capo/${FILENAME} ]
then
    SOURCE=~/.capo/${FILENAME}
else
  echo '${FILENAME} not found!'
  exit 1
fi

NEW_FILE=./test/${FILENAME}
cp ${SOURCE} ${NEW_FILE}

# remove extended attributes, which would cause Capo to balk
/usr/bin/xattr -c ${NEW_FILE}

## where the magic happens
if [ "${USE_CACHE}" == 1 ]
then
  echo '>>>> Using cache, if possible'
  docker build . -f test/Dockerfile -t ${CONTAINER_NAME}
else
  echo '>>>> no cache'
  docker build . -f test/Dockerfile --no-cache -t ${CONTAINER_NAME}
fi

# now get rid of the properties file; containing sensitive info, it must NOT be saved or committed
rm -f ${NEW_FILE}
# get rid of the .yml, too
rm -f ${ENV_YML}

# to run the image: docker run ${CONTAINER_NAME}[:latest]
