#!/usr/bin/env bash

# Please Use Google Shell Style: https://google.github.io/styleguide/shell.xml

# ---- Start unofficial bash strict mode boilerplate
# http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -o errexit  # always exit on error
set -o errtrace # trap errors in functions as well
set -o pipefail # don't ignore exit codes when piping output
set -o posix    # more strict failures in subshells
# set -x          # enable debugging

IFS=$'\n\t'
# ---- End unofficial bash strict mode boilerplate

error=""
for VAR in PROJECT SERVICE DOCKER_REPOSITORY GL_TOKEN GL_USERNAME GL_EMAIL BRANCH_TO_PUSH ENVIRONMENT; do
  if [[ -z "${VAR}" ]]; then
    error="${error}Missing required environment variable: ${VAR}\n"
  fi
done

if [[ -n "${error}" ]]; then
  echo -e "${error}" 1>&2
  exit 1
fi

SHA1=$(git rev-parse --verify HEAD)
NEW_TAG=$SHA1

# TODO: try to fix this
CURRENT_TAG=$(
  git show-ref --tags -d |
    grep "^${SHA1}" |
    sed -e 's,.* refs/tags/,,' -e 's/\^{}//' |
    grep -E "^v([0-9]+)\.([0-9]+)\.([0-9]+)(\-([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$"
    sort || true
)

if [[ -n "${CURRENT_TAG}" ]]; then
  NEW_TAG=${CURRENT_TAG}
fi

ci_scripts_dir="$(dirname "${BASH_SOURCE[0]}")"

# Install Kustomize
"${ci_scripts_dir}/install-kustomize"

# Clone goodcommerce-configuration.git repository and configure username and email for signing off commits
cd "$(mktemp -d "/tmp/gitops-XXX")"

git clone -b "${BRANCH_TO_PUSH:-"main"}" "https://${GL_USERNAME}:${GL_TOKEN}@gitlab.com/goodcommerce/core/goodcommerce-configuration.git" "configuration"
cd configuration

git config user.name "${GL_USERNAME}"
git config user.email "${GL_EMAIL}"

cd "${PROJECT:-"kustomize/overlays"}"/"${ENVIRONMENT:-"production"}"/"${SERVICE}"

# Modify image tag in kustomization.yaml by calling 'kustomize edit set image'
kustomize edit set image "${DOCKER_REPOSITORY}=${DOCKER_REPOSITORY}:${NEW_TAG}"
git add .

# Commit with sign-off
git commit -s -m "chore(deploy): changed ${SERVICE} image tag to ${NEW_TAG}"

# Push branch to origin
git push --set-upstream origin "${BRANCH_TO_PUSH:-"main"}"