#!/bin/sh

runtime_ci_event() {
  if [ -n "${CI_PIPELINE_EVENT:-}" ]; then
    printf '%s\n' "${CI_PIPELINE_EVENT}"
    return
  fi

  if [ -n "${WOODPECKER_BUILD_EVENT:-}" ]; then
    printf '%s\n' "${WOODPECKER_BUILD_EVENT}"
    return
  fi

  printf 'local\n'
}

resolve_runtime_env_name() {
  if [ -n "${CI_TARGET_ENV:-}" ]; then
    printf '%s\n' "${CI_TARGET_ENV}"
    return
  fi

  case "$(runtime_ci_event)" in
    push)
      printf 'devserver\n'
      ;;
    tag)
      printf 'prod\n'
      ;;
    *)
      printf 'prod\n'
      ;;
  esac
}

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"
}

resolve_runtime_env_file() {
  env_name="$1"
  override_file="./ci/${env_name}/.env.runtime"

  if [ ! -f "${override_file}" ]; then
    echo "[runtime-env] runtime env file not found: ${override_file}" >&2
    return 1
  fi

  if [ "${env_name}" = "prod" ]; then
    printf '%s\n' "${override_file}"
    return
  fi

  base_file="./ci/prod/.env.runtime"
  if [ ! -f "${base_file}" ]; then
    printf '%s\n' "${override_file}"
    return
  fi

  merged_file="./.runtime.${env_name}.merged.$$"
  cat "${base_file}" >"${merged_file}"
  printf '\n' >>"${merged_file}"
  cat "${override_file}" >>"${merged_file}"
  printf '%s\n' "${merged_file}"
}

load_runtime_env_bundle() {
  env_name="$1"
  runtime_file="$(resolve_runtime_env_file "${env_name}")"

  if [ -n "${VAULT_ADDR:-}" ] && [ -z "${CI_VAULT_ADDR:-}" ]; then
    export CI_VAULT_ADDR="${VAULT_ADDR}"
  fi
  if [ -n "${VAULT_ROLE_ID:-}" ] && [ -z "${CI_VAULT_ROLE_ID:-}" ]; then
    export CI_VAULT_ROLE_ID="${VAULT_ROLE_ID}"
  fi
  if [ -n "${VAULT_SECRET_ID:-}" ] && [ -z "${CI_VAULT_SECRET_ID:-}" ]; then
    export CI_VAULT_SECRET_ID="${VAULT_SECRET_ID}"
  fi

  normalize_env_file "${runtime_file}"
  normalize_env_file ./.env.version

  load_env_file "${runtime_file}"
  load_env_file ./.env.version

  export CI_RUNTIME_ENV_NAME="${env_name}"
  export RUNTIME_ENV_FILE="${runtime_file}"
}

compute_image_tag() {
  : "${APP_V:?missing APP_V}"
  : "${GIT_REV:?missing GIT_REV}"
  printf '%s-%s\n' "${APP_V}" "${GIT_REV}"
}
