#!/usr/bin/env bash
set -e
set -o pipefail

if [[ -z "$CPAAS_PRODUCT_VERSION" ]]; then
   echo "ERROR: Environment variable CPAAS_PRODUCT_VERSION not defined."
   exit 2
fi

# Import environment variables. We need to define them in a separate file
# to be templated from `render_vars.in` and rendered by the midstream automation
source render_vars

# Directory where the operator code is cloned
codebase_dir=$(pwd)/apicast-operator
# Distgit directory = Current directory
distgit_root=$(pwd)

# Temporary directory for the tool binaries
tmpbin_dir=$(pwd)/bin
mkdir "$tmpbin_dir"


# Clone the codebase
git config --global core.sshCommand 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
git clone "$UPSTREAM_GIT_URL" "$codebase_dir"
if [[ $? -ne 0 ]]; then
   echo "ERROR: Could not clone upstream release repo."
   exit 2
fi

# cd into the code dir and checkout the specific commit
cd "$codebase_dir"
git checkout "$UPSTREAM_GIT_COMMIT"
cd "$distgit_root"

download_binary() {
  base_url=$1
  binary_name=$2
  command_name=$3
  curl -LO "$base_url"/"$binary_name"
  chmod +x "$binary_name"
  mv "$binary_name" "$tmpbin_dir"/"$command_name"
}

# Get yq
download_binary https://github.com/mikefarah/yq/releases/download/v4.20.2 yq_linux_amd64 yq
YQ=$tmpbin_dir/yq

echo $YQ

make generate-bundles STREAM=stable UPSTREAM_BUNDLE_DIR="$codebase_dir/bundle" DOWNSTREAM_BUNDLE_DIR=./ YQ=$YQ


cd "$distgit_root"
rm -rf $codebase_dir
rm -rf $tmpbin_dir

exit 0
