#!/usr/bin/env bash

set -euo pipefail

commands=(
  "annotate"
  "annotation remove"
  "artifact download"
  "artifact shasum"
  "artifact upload"
  "artifact search"
  "bootstrap"
  "build cancel"
  "env dump"
  "env set"
  "env get"
  "env unset"
  "lock acquire"
  "lock do"
  "lock done"
  "lock get"
  "lock release"
  "meta-data exists"
  "meta-data get"
  "meta-data keys"
  "meta-data set"
  "oidc request-token"
  "pause"
  "pipeline upload"
  "redactor add"
  "resume"
  "secret get"
  "start"
  "step get"
  "step update"
  "step cancel"
  "stop"
  "tool keygen"
  "tool sign"
)

scripts_dir=$(dirname "${BASH_SOURCE[0]}")
base_dir=$(git rev-parse --show-toplevel)

for command in "${commands[@]}"; do
  file="${base_dir}/pages/agent/v3/help/_${command//[- ]/_}.md"
  if [[ ! -f "$file" ]]; then
    echo "File $file doesn't exist"
    exit 1
  fi

  echo Updating docs for buildkite-agent "$command"

  cat << 'EOF' >"$file"
<!--
  _____   ____    _   _  ____ _______   ______ _____ _____ _______
 |  __ \ / __ \  | \ | |/ __ \__   __| |  ____|  __ \_   _|__   __|
 | |  | | |  | | |  \| | |  | | | |    | |__  | |  | || |    | |
 | |  | | |  | | | . ` | |  | | | |    |  __| | |  | || |    | |
 | |__| | |__| | | |\  | |__| | | |    | |____| |__| || |_   | |
 |_____/ \____/  |_| \_|\____/  |_|    |______|_____/_____|  |_|

This file is auto-generated by scripts/update-agent-help.sh, please update the
agent CLI help in https://github.com/buildkite/agent and run the generation
script.

-->

EOF

  # shellcheck disable=SC2086
  buildkite-agent $command --help | \
    ruby "${scripts_dir}/cli2md.rb" >>"$file"
done
