#!/usr/bin/env bash

set -e

scriptDir=$(dirname $0)
cflibDir=$scriptDir/../../cflib
apiRefDir=$scriptDir/../../docs/api
templateDir=$apiRefDir/template
tempDir=$scriptDir/../../.tmp

mkdir -p $apiRefDir
mkdir -p $tempDir

[ -n "$API_REF_BASE" ] || {
    export API_REF_BASE=$(readlink -fn $tempDir)
}

#
# If cflib is not installed (mostly its dependencies) then pdoc3 cannot
# traverse the library and get docstrings.
#
# The rewriting of HOME is a hack to make this work in a bare-bone Docker
# environment.
#

# Make a temporary install in the temp dir
HOME=$tempDir pip3 install --upgrade pip
HOME=$tempDir pip3 install -e $scriptDir/../../

# Generate documentation
HOME=$tempDir pdoc3 --force $cflibDir --output-dir $tempDir --template-dir $templateDir

# Modify the generated content to fit our file tree
## Rename root file that will be included in another md file
rootFile=$tempDir/cflib/index.md_raw
mv $tempDir/cflib/index.md $rootFile
## Remove the front matter at the top
sed -i '1,4d' $rootFile
## Links are not processed properly in the included content. Hack it by removing index.md
sed -i s/index\.md// $rootFile

# Copy to the md file tree
cp -r $tempDir/cflib/* $apiRefDir/cflib/.

# Clean up
rm -r $tempDir
