#!/usr/bin/env bash

source $(dirname ${0})/functions.sh

# Makes sure we activate the base environment if available
run_cmd source ${CONDA_ROOT}/etc/profile.d/conda.sh
run_cmd conda activate base
export_env PATH

if [ -z "${BOB_BUILD_NUMBER}" ]; then
  set_conda_channels ${VISIBILITY} ${CI_COMMIT_TAG}
  set_next_bob_build_number ${CONDA_CHANNELS[0]}
fi

# copy the recipe_append.yaml over before build
run_cmd cp ${SCRIPTS_DIR}/recipe_append.yaml conda/recipe_append.yaml

BLDOPT="--no-anaconda-upload"
BLDOPT="${BLDOPT} --variant-config-files ${SCRIPTS_DIR}/conda_build_config.yaml"
BLDOPT="${BLDOPT} --python=${PYTHON_VERSION}"

if [ -n "${BOB_TEST_ONLY}" ]; then
  log_info "Running ${CONDA_ROOT}/bin/conda build ${BLDOPT} --output conda to generate package name..."
  tarball=$(${CONDA_ROOT}/bin/conda build ${BLDOPT} --output conda)
  if [ -z "${tarball}" ]; then
    log_info "Package ${CI_PROJECT_PATH} is NOT supposed to be built for ${OS_SLUG}/python${PYTHON_VERSION} (cannot generate tarball name). Skipping..."
    exit 0
  fi
  log_info "Only testing package ${tarball}..."
  set_conda_channels ${VISIBILITY} ${CI_COMMIT_TAG}
  if [ ! -r "${tarball}" ]; then
    log_info "Package ${tarball} does not exist locally - checking channel ${CONDA_CHANNELS[0]}..."
    remote_name="${CONDA_CHANNELS[0]}/${OS_SLUG}/$(basename ${tarball})"
    if url_exists ${remote_name}; then
      log_info "Conda tarball exists in remote location, downloading..."
      url_get ${tarball} ${remote_name}
    else
      log_warn "Package $(basename ${tarball}) does not exist at ${remote_name} - aborting..."
      exit 1
		fi
  fi
  BLDOPT="${BLDOPT} --test"
  run_cmd ${CONDA_ROOT}/bin/conda build ${BLDOPT} ${tarball}
else
  log_info "Building and testing package..."
  run_cmd ${CONDA_ROOT}/bin/conda build ${BLDOPT} conda
fi

log_error "KABOOOOOOOOOOOOOOOOOOOMMMMMMMMMMMMMMMMMMMMM!"
log_error "Your build will fail just because you did not read your e-mails!"
log_error "Here, let me take your hand... Type on your prompt:"
log_error "$ cd mypackage"
log_error "$ git checkout master"
log_error "$ curl -o .gitlab-ci.yml https://gitlab.idiap.ch/bob/bob.devtools/blob/master/bob/devtools/templates/.gitlab-ci.yml"
log_error "$ git commit -m '[ci] Updated CI - sorry for the trouble' .gitlab-ci.yml"
log_error "$ git push"
log_error ""
log_error "Meanwhile, you'll have to live with this (shameful) failure..."
log_error "Enjoy!"
exit 1