#!/bin/sh

# This script builds the static documentation site. You need to have Gradle and
# MkDocs set up and working on your system to run it.

set -x
set -e
set -u
cd "$(dirname "$0")/.."

if [ $# -ne 1 ] ; then
	echo "usage: $0 OUTPUT_DIR" 1>&2
	exit 1
fi

OUTPUT_DIR="$1"
if [ ! -d "$OUTPUT_DIR" ] ; then
	mkdir -p "$OUTPUT_DIR"
fi
OUTPUT_DIR="$(realpath "$OUTPUT_DIR")"

TEMP="$(mktemp -d)"
trap "rm -rf '$TEMP'" EXIT

./gradlew build javadoc -x test -x autoLintGradle -x lint

cp -R ./docs/site/* "$TEMP"
cp -R ./docs/models "$TEMP/docs/"
cp -R ./docs/sdks "$TEMP/docs/"
mkdir "$TEMP/javadoc"
cp -R ./build/docs/javadoc/* "$TEMP/javadoc"

cd "$TEMP"

printf '# Index of Models Documentation\n\nThese documents are auto-generated by Speakeasy.\n\n' > docs/models/index.md
find ./docs/models/ -type f -iname "*.md" | grep -v 'index.md$' | while read -r f ; do
	# extract the title frome each markdown file
	t="$(awk '/^[#]/ {$1=""; print($0); exit}' < "$f" | sed 's/^ //g')"

	# generate an appropriate link based on the file path
	l="$(echo "$f" | sed 's#^./docs/models/#./#g')"

	# append the link to the index file
	printf '* [%s](%s)\n' "$t" "$l" >> docs/models/index.md
done

printf '# Index of SDKs Documentation\n\nThese documents are auto-generated by Speakeasy.\n\n' > docs/sdks/index.md
find ./docs/sdks/ -type f -iname "*.md" | grep -v 'index.md$' | while read -r f ; do
	# extract the title frome each markdown file
	t="$(awk '/^[#]/ {$1=""; print($0); exit}' < "$f" | sed 's/^ //g')"

	# generate an appropriate link based on the file path
	l="$(echo "$f" | sed 's#^./docs/sdks/#./#g')"

	# append the link to the index file
	printf '* [%s](%s)\n' "$t" "$l" >> docs/sdks/index.md
done

mkdocs build -d "$OUTPUT_DIR"
cp -R javadoc "$OUTPUT_DIR"

