#!/usr/bin/env bash
# Thu 22 Sep 2016 13:05:54 CEST

# Installation script for our build tools

if [ "${#}" -ne 1 ]; then
  echo "usage: ${0} <ci-support-directory>"
  echo "example: ${0} _ci"
  exit 1
fi


# Functions for coloring echo commands
log_info() {
  echo -e "(`date +%T`) \033[1;34m${@}\033[0m"
}


log_error() {
  echo -e "(`date +%T`) \033[1;31mError: ${@}\033[0m"
}


# Function for running command and echoing results
run_cmd() {
  log_info "$ ${@}"
  ${@}
  local status=$?
  if [ ${status} != 0 ]; then
    log_error "Command Failed \"${@}\""
    exit ${status}
  fi
}


get_script() {
  local curlopt="--location --silent --show-error --output ${1}/${2}"
  if [ -e ${1}/${2} ]; then #check for updates
    local checkopt="${curlopt} --time-cond ${1}/${2} --silent"
    checkopt="${checkopt} --write-out %{http_code}"
    if [ "$(curl ${checkopt})" == "200" ]; then
      log_info "CI script ${1}/${2} needs updating..."
      rm -f ${1}/${2}
    else
      log_info "CI script ${1}/${2} is up-to-date"
      return 0
    fi
  fi
  # check file needs updating
  local url="https://gitlab.idiap.ch/bob/bob.admin/raw/master/gitlab/${2}"
  run_cmd curl ${curlopt} ${url}
}


get_exec() {
  get_script ${1} ${2}
  chmod 755 ${1}/${2}
}


run_cmd mkdir -pv ${1}
get_script ${1} functions.sh
get_script ${1} install.sh
for stage in "build" "test" "wheels" "deploy"; do
  get_exec ${1} before_${stage}.sh
  get_exec ${1} ${stage}.sh
  get_exec ${1} after_${stage}.sh
done