#!/bin/real-bash
# shellcheck shell=bash

# cci-export is a function which can be used to export environment variables in a way that is persistent
# across CircleCI steps.
cci-export() {
  if [ "$#" -ne 2 ]; then
    echo >&2 "Usage: $0 KEY VALUE"
    return 1
  fi

  key="$1"
  value="$2"

  export "${key}=${value}"

  if [[ "$CIRCLECI" == "true" ]]; then
    if [[ -z "${BASH_ENV}" ]]; then
      echo >&2 "Env var BASH_ENV not properly set"
      return 1
    fi

    # Use export with default value in the following form
    # export __CCI_EXPORT_FOO_VALUE=bar
    # export FOO="${FOO-"${__CCI_EXPORT_FOO_VALUE}"}"'
    # for the following reasons:
    # - Using Bash default value (FOO=${FOO-"${__CCI_EXPORT_FOO_VALUE}"}) - so that variables already set in the
    #   environment are not overwritten by `$BASH_ENV` (including variables set to empty string).
    # - Using a variable holding the default value (__CCI_EXPORT_FOO_VALUE=value) - so that multiline values (e.g.
    #   certificates) are correctly escaped.
    #
    # An example of BASH_ENV contents:
    # export __CCI_EXPORT_FOO_VALUE=bar
    # export FOO="${FOO-"${__CCI_EXPORT_FOO_VALUE}"}"'
    # export __CCI_EXPORT_BAZ_VALUE=baz
    # export BAZ="${BAZ-"${__CCI_EXPORT_BAZ_VALUE}"}"'

    shadow_key="__CCI_EXPORT_${key}_VALUE"

    # Remove all lines starting with:
    # export __CCI_EXPORT_VAR_VALUE=
    # export VAR=
    # for the same exported variable (VAR), to 'forget' about past cci-export calls,
    # otherwise the first call to cci-export would define a default value for the variable, so that
    # second and subsequent calls to cci-export would have no effect.
    if [[ -f "$BASH_ENV" ]]; then
      filtered_envfile="$(mktemp -t "bash.env-XXXX")"
      # The first pattern (-e) is necessary for correctness
      # The second pattern is optional for correctness, but it prevents duplicate lines cluttering the file
      grep --invert-match --fixed-strings \
        -e "export ${shadow_key}=" \
        -e "export ${key}=" \
        "$BASH_ENV" > "${filtered_envfile}" && mv "${filtered_envfile}" "$BASH_ENV"
    fi

    printf "export %s=%q\n" "$shadow_key" "$value" >> "$BASH_ENV"
    # shellcheck disable=SC2016 # we must produce literal ${} symbols
    printf 'export %s="${%s-"${%s}"}"\n' "$key" "$key" "$shadow_key" >> "$BASH_ENV"
  fi
}

export -f cci-export

exec /bin/real-bash "$@"
