#!/bin/bash

# ----- Check for dependencies

JAZZY=$(which jazzy)
if [ $? != 0 ]; then
    echo -e "Jazzy is required to generate documentation. Install it with:\n"
    echo -e "    gem install jazzy\n"
    exit
fi
echo "Using jazzy: $JAZZY"


# ----- Commandline options

if [ "$BRANCH" == "" ]; then
  BRANCH=$([ "$1" == "" ] && echo "master" || echo "$1")
fi

if [ "$OUTPUT_PATH" == "" ]; then
  OUTPUT_PATH=$([ "$2" == "" ] && echo "Docs/output/$BRANCH" || echo "$2")
fi


# ----- Configuration

ORGANISATION=ReSwift
NAME=ReSwift
TMP=Docs/tmp
GITHUB=https://github.com/$ORGANISATION/$NAME
URL=http://$ORGANISATION.github.io/$NAME

PREPROC=.scripts/doc-preprocessor

# ----- Setup and generate docs

# Clean $TMP folder
if [ -d "$TMP" ]; then rm -rf "$TMP"; fi
mkdir -p $TMP/{compile,docs,api}

cp Docs/*.md $TMP/api/

# Split the README into sections
$PREPROC README.md "$TMP/docs/About ReSwift.md" --section "About ReSwift" --title "About ReSwift"
$PREPROC README.md "$TMP/docs/Why ReSwift.md" --section "Why ReSwift?" --title "Why ReSwift?"
$PREPROC README.md "$TMP/docs/Installation.md" --section "Installation" --title "Installation"
$PREPROC README.md "$TMP/docs/Checking out Source Code.md" --section "Checking out Source Code" --title "Checking out Source Code"
$PREPROC README.md "$TMP/docs/Demo.md" --section "Demo" --title "Demo"
$PREPROC README.md "$TMP/docs/Extensions.md" --section "Extensions" --title "Extensions"
$PREPROC README.md "$TMP/docs/Example Projects.md" --section "Example Projects" --title "Example Projects"
$PREPROC README.md "$TMP/docs/Credits.md" --section "Credits" --title "Credits"
$PREPROC README.md "$TMP/docs/Get in touch.md" --section "Get in touch" --title "Get in touch"
$PREPROC README.md "$TMP/compile/intro.md" --section "Introduction"

# Copy remaining root docs
$PREPROC CONTRIBUTING.md "$TMP/docs/Contributing.md"
$PREPROC CHANGELOG.md "$TMP/docs/Changelog.md" --title "Changelog"
$PREPROC LICENSE.md "$TMP/docs/License.md" --title "License"

# Copy over the Getting started guide
$PREPROC "Docs/Getting Started Guide.md" "$TMP/docs/Getting Started Guide.md"

# Create the documentation landing page by combining:
#
# - Docs/templates/heading.md
# - README.md#introduction
# - Docs/templates/toc.md
#
cat Docs/templates/heading.md $TMP/compile/intro.md Docs/templates/toc.md > $TMP/compile/readme-raw.md
$PREPROC "$TMP/compile/readme-raw.md" "$TMP/compile/README.md"
cp $TMP/compile/README.md $TMP/api/Documentation.md

# Compile our Docs/tmp + generate API docs using jazzy
jazzy \
  --config .jazzy.json \
  --clean \
  --output "$OUTPUT_PATH" \
  --module-version "$BRANCH" \
  --dash_url "$URL/$BRANCH/docsets/$NAME.xml" \
  --root-url "$URL/$BRANCH/" \
  --github_url "$GITHUB" \
  --github-file-prefix "$GITHUB/tree/$BRANCH"

cp Docs/img/* $OUTPUT_PATH/img/
