#
# Normalized CI environment variables
#
# |source| me
#

if [[ -n $CI ]]; then
  export CI=1
  if [[ -n $BUILDKITE ]]; then
    export CI_BRANCH=$BUILDKITE_BRANCH
    export CI_BUILD_ID=$BUILDKITE_BUILD_ID
    if [[ $BUILDKITE_COMMIT = HEAD ]]; then
      BUILDKITE_COMMIT="$(git rev-parse HEAD)"
    fi
    export CI_COMMIT=$BUILDKITE_COMMIT
    export CI_JOB_ID=$BUILDKITE_JOB_ID
    # The standard BUILDKITE_PULL_REQUEST environment variable is always "false" due
    # to how solana-ci-gate is used to trigger PR builds rather than using the
    # standard Buildkite PR trigger.
    if [[ $CI_BRANCH =~ pull/* ]]; then
      export CI_BASE_BRANCH=$BUILDKITE_PULL_REQUEST_BASE_BRANCH
      export CI_PULL_REQUEST=true
    else
      export CI_BASE_BRANCH=$BUILDKITE_BRANCH
      export CI_PULL_REQUEST=
    fi

    if [[ -n $BUILDKITE_TRIGGERED_FROM_BUILD_PIPELINE_SLUG ]]; then
      # The solana-secondary pipeline should use the slug of the pipeline that
      # triggered it
      export CI_REPO_SLUG=$BUILDKITE_ORGANIZATION_SLUG/$BUILDKITE_TRIGGERED_FROM_BUILD_PIPELINE_SLUG
    else
      export CI_REPO_SLUG=$BUILDKITE_ORGANIZATION_SLUG/$BUILDKITE_PIPELINE_SLUG
    fi
    # TRIGGERED_BUILDKITE_TAG is a workaround to propagate BUILDKITE_TAG into
    # the solana-secondary pipeline
    if [[ -n $TRIGGERED_BUILDKITE_TAG ]]; then
      export CI_TAG=$TRIGGERED_BUILDKITE_TAG
    else
      export CI_TAG=$BUILDKITE_TAG
    fi

  elif [[ $GITHUB_ACTION ]]; then
    export CI_BUILD_ID=$GITHUB_RUN_ID
    export CI_JOB_ID=$GITHUB_RUN_NUMBER
    export CI_REPO_SLUG=$GITHUB_REPOSITORY
    export CI_BRANCH=$GITHUB_REF_NAME

    CI_COMMIT=$(git rev-parse HEAD)
    export CI_COMMIT

    CI_TAG=$(git tag --points-at HEAD)
    export CI_TAG

    if [[ $GITHUB_BASE_REF ]]; then
      export CI_BASE_BRANCH=$GITHUB_BASE_REF
      export CI_PULL_REQUEST=true
    fi
  fi

  _arch="$(uname -m)"
  if [[ $_arch = arm64 ]]; then
    _arch=aarch64
  fi

  case $(uname | tr '[:upper:]' '[:lower:]') in
  linux*)
    export CI_OS_NAME=linux
    export CI_BUILD_TARGET_TRIPLE="$_arch-unknown-linux-gnu"
    ;;
  darwin*)
    export CI_OS_NAME=osx
    export CI_BUILD_TARGET_TRIPLE="$_arch-apple-darwin"
    ;;
  msys*)
    export CI_OS_NAME=windows
    export CI_BUILD_TARGET_TRIPLE="$_arch-pc-windows-msvc"
    ;;
  *)
    ;;
  esac
else
  export CI=
  export CI_BRANCH=
  export CI_BASE_BRANCH=
  export CI_BUILD_ID=
  export CI_COMMIT=
  export CI_JOB_ID=
  export CI_PULL_REQUEST=
  export CI_REPO_SLUG=
  export CI_TAG=
  export CI_BUILD_TARGET_TRIPLE
  # Don't override ci/run-local.sh
  if [[ -z $CI_LOCAL_RUN ]]; then
    export CI_OS_NAME=
  fi
fi

cat <<EOF
CI=$CI
CI_BRANCH=$CI_BRANCH
CI_BASE_BRANCH=$CI_BASE_BRANCH
CI_BUILD_ID=$CI_BUILD_ID
CI_BUILD_TARGET_TRIPLE=$CI_BUILD_TARGET_TRIPLE
CI_COMMIT=$CI_COMMIT
CI_JOB_ID=$CI_JOB_ID
CI_PULL_REQUEST=$CI_PULL_REQUEST
CI_OS_NAME=$CI_OS_NAME
CI_REPO_SLUG=$CI_REPO_SLUG
CI_TAG=$CI_TAG
EOF
