#!/usr/bin/env bash

# Copyright 2025 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.

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

# This script "freezes" the docs folder, copying docs which are relevant for a
# specific cert-manager release into their own folder so they can be browsed
# individually.
#
# For example, upon the release of cert-manager v1.17 we use this script to
# "freeze" cert-manager v1.16, creating content/v1.16-docs and removing some
# fields which aren't relevant (such as release notes or "contributing" docs)

RELEASE=${1:-}

if [[ -z "${RELEASE}" ]]; then
	echo "usage: $0 <release-version>"
	echo "For examplem, if you are releasing cert-manager v1.20.0:"
	echo "  $0 1.19 "
	exit 1
fi

cp -r content/docs content/v${RELEASE}-docs

# Delete any folders in the new v$RELEASE-docs section which contain a file
# named ".x-only-docs"
rm -rf $(find content/v${RELEASE}-docs -name ".x-only-docs" -execdir pwd \;)

TMP_FILE=$(mktemp)

trap "rm -rf ${TMP_FILE}" EXIT

# Replace paths containing /docs/ with a versioned path
sed "s|/docs/|/v${RELEASE}-docs/|g" content/v${RELEASE}-docs/manifest.json >$TMP_FILE

# Remove any parts of the manifest which have "x-only-docs": true
jq <$TMP_FILE >content/v${RELEASE}-docs/manifest.json \
	'del(.routes[0].routes[] | select(."x-only-docs" == true))'
