#!/bin/sh
set -eu

if ! set -o pipefail 2>/dev/null; then
  :
fi

REPO_ROOT="$(cd "$(dirname "$0")/../../.." && pwd)"
cd "${REPO_ROOT}"

sh ci/scripts/common/ensure_env_version.sh
. ci/scripts/common/runtime_env.sh

normalize_env_file() {
  file="$1"
  tmp="${file}.tmp.$$"
  tr -d '\r' <"$file" >"$tmp"
  mv "$tmp" "$file"
}

load_env_file() {
  file="$1"
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      ''|\#*) continue ;;
    esac
    key="${line%%=*}"
    value="${line#*=}"
    key="$(printf '%s' "$key" | tr -d '[:space:]')"
    value="${value#"${value%%[![:space:]]*}"}"
    value="${value%"${value##*[![:space:]]}"}"
    export "$key=$value"
  done <"$file"
}

CALLBACKS_ENV_NAME="${CALLBACKS_ENV:-$(resolve_runtime_env_name)}"
load_runtime_env_bundle "${CALLBACKS_ENV_NAME}"

IMAGE_TAG="$(compute_image_tag)"
CALLBACKS_CONFIG_PATH="api/edge/callbacks/config.yml"
if [ "${CI_RUNTIME_ENV_NAME:-prod}" = "devserver" ] && [ -f "${REPO_ROOT}/api/edge/callbacks/config.dev.yml" ]; then
  CALLBACKS_CONFIG_PATH="api/edge/callbacks/config.dev.yml"
fi

REGISTRY_URL="${REGISTRY_URL:?missing REGISTRY_URL}"
APP_V="${APP_V:?missing APP_V}"
CALLBACKS_DOCKERFILE="${CALLBACKS_DOCKERFILE:?missing CALLBACKS_DOCKERFILE}"
CALLBACKS_IMAGE_PATH="${CALLBACKS_IMAGE_PATH:?missing CALLBACKS_IMAGE_PATH}"

REGISTRY_HOST="${REGISTRY_URL#http://}"
REGISTRY_HOST="${REGISTRY_HOST#https://}"
REGISTRY_USER="$(cat secrets/REGISTRY_USER)"
REGISTRY_PASSWORD="$(cat secrets/REGISTRY_PASSWORD)"
: "${REGISTRY_USER:?missing registry user}"
: "${REGISTRY_PASSWORD:?missing registry password}"

mkdir -p /kaniko/.docker
AUTH_B64="$(printf '%s:%s' "$REGISTRY_USER" "$REGISTRY_PASSWORD" | base64 | tr -d '\n')"
cat <<JSON >/kaniko/.docker/config.json
{
  "auths": {
    "https://${REGISTRY_HOST}": { "auth": "${AUTH_B64}" }
  }
}
JSON

BUILD_CONTEXT="${CALLBACKS_BUILD_CONTEXT:-${WOODPECKER_WORKSPACE:-${CI_WORKSPACE:-${PWD:-/workspace}}}}"
if [ ! -d "${BUILD_CONTEXT}" ]; then
  BUILD_CONTEXT="/workspace"
fi

/kaniko/executor \
  --context "${BUILD_CONTEXT}" \
  --dockerfile "${CALLBACKS_DOCKERFILE}" \
  --destination "${REGISTRY_URL}/${CALLBACKS_IMAGE_PATH}:${IMAGE_TAG}" \
  --build-arg APP_CONFIG_PATH="${CALLBACKS_CONFIG_PATH}" \
  --build-arg APP_VERSION="${APP_V}" \
  --build-arg GIT_REV="${GIT_REV}" \
  --build-arg BUILD_BRANCH="${BUILD_BRANCH}" \
  --build-arg BUILD_DATE="${BUILD_DATE}" \
  --build-arg BUILD_USER="${BUILD_USER}" \
  --single-snapshot
