#!/usr/bin/env bash

###### script header ######

lib=$(realpath @@BASE_LIB@@) || exit 1
stat "${lib}" >> /dev/null || exit 1

# shellcheck source=../sh/lib.bash
if ! source "${lib}"; then
  echo "Error: could not find import"
  exit 1
fi

cd "${BUILD_WORKSPACE_DIRECTORY}"

###### script body ######

bazelVer=$(cat .bazelversion) # has no v prefix

bazelVerContainerfileRegex='(ARG BAZEL_VERSION=)([0-9]+\.[0-9]+\.[0-9]+)'
if [[ ! "$(cat bazel/container/Containerfile)" =~ ${bazelVerContainerfileRegex} ]]; then
  echo "Error: no match found in Containerfile"
  exit 1
fi

bazelVerContainerfile="${BASH_REMATCH[2]}"

if [[ ${bazelVer} != "${bazelVerContainerfile}" ]]; then
  sed -r -i "s/${bazelVerContainerfileRegex}/\\1${bazelVer}/" bazel/container/Containerfile
  echo "Containerfile updated, was previously at ${bazelVerContainerfile}"
fi

bazelVerScriptRegex='(containerImage="ghcr.io/edgelesssys/bazel-container:v)([0-9]+\.[0-9]+\.[0-9]+)'
if [[ ! "$(cat bazel/container/container.sh)" =~ ${bazelVerScriptRegex} ]]; then
  echo "Error: no match found in container.sh"
  exit 1
fi

bazelVerScript="${BASH_REMATCH[2]}"

if [[ ${bazelVer} != "${bazelVerScript}" ]]; then
  # bazelVerScriptRegex contains slashes, so use % as delimiter
  sed -r -i "s%${bazelVerScriptRegex}%\\1${bazelVer}%" bazel/container/container.sh
  echo "container.sh updated, was previously at ${bazelVerScript}"
fi
