#!/bin/bash

set -euo pipefail

function retry {
    local retries=$1
    shift

    local count=0
    until "$@"; do
        exit=$?
        wait=$((2 ** count))
        count=$((count + 1))
        if [ $count -lt "$retries" ]; then
            >&2 echo "Retry $count/$retries exited $exit, retrying in $wait seconds..."
            sleep $wait
        else
            >&2 echo "Retry $count/$retries exited $exit, no more retries left."
            return $exit
        fi
    done
    return 0
}

export BUILD_MACHINE_TYPE="n2-standard-4"

function configure_elasticmachine_ssh_key {
    # Temporary workaround until we can move to HTTPS auth.
    # Fetch SSH keys while the job Vault token is still valid.
    mkdir -p "$HOME/.ssh"
    retry 5 vault read -field=private-key secret/ci/elastic-docs/elasticmachine-ssh-key > "$HOME/.ssh/id_rsa"
    retry 5 vault read -field=public-key secret/ci/elastic-docs/elasticmachine-ssh-key > "$HOME/.ssh/id_rsa.pub"
    chmod 600 "$HOME/.ssh/id_rsa"
}

# Secrets must be redacted
# https://buildkite.com/docs/pipelines/managing-log-output#redacted-environment-variables
if [[ "$BUILDKITE_PIPELINE_SLUG" == "docs-build-pr" ]];then
    export BUILDKITE_API_TOKEN=$(retry 5 vault kv get -field=value secret/ci/elastic-docs/buildkite_token)
    configure_elasticmachine_ssh_key
    if [[ ${GITHUB_PR_BASE_REPO:="unset"} == "docs" ]]; then
        # Docs PR require a full rebuild - so let's boost the builds so they don't take 2 hours
        export BUILD_MACHINE_TYPE="n2-highcpu-32"
    fi
elif [[ "$BUILDKITE_PIPELINE_SLUG" == "docs-build" ]];then
    export BUILD_MACHINE_TYPE="n2-highcpu-32"
    export BUILDKITE_API_TOKEN=$(retry 5 vault kv get -field=value secret/ci/elastic-docs/buildkite_token)
    configure_elasticmachine_ssh_key
elif [[ "$BUILDKITE_PIPELINE_SLUG" == "docs-build-air-gapped" ]] && [[ "$BUILDKITE_STEP_KEY" == "publish-air-gapped-doc" ]]; then
    export DOCKER_USERNAME=$(retry 5 vault kv get -field=username secret/ci/elastic-docs/docker.elastic.co)
    export DOCKER_PASSWORD=$(retry 5 vault kv get -field=password secret/ci/elastic-docs/docker.elastic.co)
fi

if [[ "$BUILDKITE_PIPELINE_SLUG" == "docs-build-pr" ]] && [[ "$BUILDKITE_STEP_KEY" == "build-pr" ]]; then
    "${BUILDKITE_BUILD_CHECKOUT_PATH}/.buildkite/scripts/build_pr_commit_status.sh" pending || true
fi
