#!/usr/bin/env bash

# Copyright 2022 The cert-manager Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script constructs a 'content/' directory that contains content for all
# configured versions of the documentation which use the "github.com/cert-manager/cert-manager" import path

set -o errexit
set -o nounset
set -o pipefail

REPO_ROOT="${REPO_ROOT:-$(cd "$(dirname "$0")/../.." && pwd)}"

if ! command -v go &>/dev/null; then
  echo "Ensure go is installed"
  exit 1
fi

if ! command -v npm &>/dev/null; then
  echo "Ensure npm is installed"
  exit 1
fi

tmpdir="$(mktemp -d)"
apidocstmpdir="$(mktemp -d)"

cleanup() {
  echo "+++ Cleaning up temporary GOPATH"
  rm -rf "${apidocstmpdir}"
  rm -rf "${tmpdir}"
}
trap cleanup EXIT

GOMODCACHE="$(go env GOMODCACHE)"
export GOMODCACHE

# Create fake GOPATH
echo "+++ Creating temporary GOPATH"
export GOPATH="${tmpdir}/go"
export GO111MODULE="on"
GOROOT="$(go env GOROOT)"
export GOROOT
GOBIN="${tmpdir}/bin"
export GOBIN

go install github.com/ahmetb/gen-crd-api-reference-docs@v0.3.0

# genversion takes two arguments (branch in cert-manager repo and a directory in
# this repo under content) and generates API reference docs from cert-manager
# branch for the path in this repo.
genversion() {
  checkout "$1"
  gendocs "$2"
}

genversionwithcli() {
  genversion "$1" "$2"

  genclireference "$2" "cmd/acmesolver" "acmesolver"
  genclireference "$2" "cmd/cainjector" "cainjector"
  genclireference "$2" "cmd/ctl" "cmctl"
  genclireference "$2" "cmd/controller" "controller"
  genclireference "$2" "cmd/webhook" "webhook"
  genclireference "$2" "cmd/startupapicheck" "startupapicheck"

  # if any of the above steps succeeded copy over the index file
  if [ "$2" != "docs" ] && [ -d "$REPO_ROOT/content/$2/cli" ]; then
    cp "$REPO_ROOT/content/docs/cli/README.md" "${REPO_ROOT}/content/$2/cli/"
  fi
}

checkout() {
  branch="$1"

  mkdir -p "${GOPATH}/src/github.com/cert-manager"
  gitdir="${GOPATH}/src/github.com/cert-manager/cert-manager"
  echo "+++ Cloning cert-manager repository..."
  git clone "https://github.com/cert-manager/cert-manager.git" "$gitdir" --depth 1 --branch="$branch"
  cd "$gitdir"
  echo "+++ Running 'go mod vendor'"
  go mod vendor

  make go-workspace || true
}

gendocs() {
  outputdir="$1"
  mkdir -p "${apidocstmpdir}/${outputdir}/"
  echo "+++ Generating reference docs..."
  "${GOBIN}/gen-crd-api-reference-docs" \
    -config "${REPO_ROOT}/scripts/gendocs/config.json" \
    -template-dir "${REPO_ROOT}/scripts/gendocs/templates" \
    -api-dir "./pkg/apis" \
    -out-file "${apidocstmpdir}/${outputdir}/api-docs.md"

  "${REPO_ROOT}"/scripts/gendocs/postprocess/api-doc-postprocess.js <"${apidocstmpdir}/${outputdir}/api-docs.md" >"${REPO_ROOT}/content/${outputdir}/reference/api-docs.md"

  rm -rf vendor/
}

# genclireference will attempt to run main.go --help for the target and write the output to a markdown file
genclireference() {
  if [ ! -f "$2/main.go" ]; then
    echo "+++ target $2 does not exist, skipping..."
    return
  fi

  outputdir="$1"
  target="$2"
  name="$3"
  echo "+++ Generating CLI reference docs for $target ..."

  mkdir -p "${REPO_ROOT}/content/${outputdir}/cli/"

  output=$(go run "$target/main.go" --help)
  cat >"${REPO_ROOT}/content/${outputdir}/cli/$name.md" <<EOF
---
title: $name CLI reference
description: "cert-manager $name CLI documentation"
---
\`\`\`
$output
\`\`\`
EOF
}

# For final releases such as v1.20.0, DOCS_FOLDER should be `docs` (or a
# versioned docs folder name such as `v1.20-docs`), and CM_BRANCH should be
# the release branch, e.g. `release-1.20`.
CM_BRANCH="release-1.21"
DOCS_FOLDER="docs"

genversionwithcli "$CM_BRANCH" "$DOCS_FOLDER"

# Rather than generate the same docs again for /docs, copy from the latest version

cp -r "${REPO_ROOT}/content/${DOCS_FOLDER}/cli" "${REPO_ROOT}/content/docs/"
cp "${REPO_ROOT}/content/${DOCS_FOLDER}/reference/api-docs.md" "${REPO_ROOT}/content/docs/reference/"

echo "Generated reference documentation for cert-manager versions with the github.com/cert-manager/cert-manager import path"
