#!/bin/bash

export VERSIONER_PYTHON_VERSION=2.6
export VERSIONER_PYTHON_PREFER_32_BIT=yes

echo "Fetching documentation, this needs to run in the VPN..."

if [ -d "input" ]; then
  rm -rf input
fi

if [ -d "output" ]; then
  rm -rf input
fi

if [ ! -d "../res/DocLibrary" ]; then
  mkdir  -p ../res/DocLibrary
fi

rm -f ../res/DocLibrary/*

mkdir input

wget http://mydocs.no.oracle.com/docs-confidential/workbench-next/en/html-guitools.zip -O input/wb-html-guitools.zip

result=$?
if [ $result -ne 0 ]; then
    echo "[Error: $result] Failed to get http://mydocs.no.oracle.com/docs-confidential/workbench-next/en/html-guitools.zip"
    exit 1
fi

# wget http://mydocs.no.oracle.com/docs/refman-5.6/en/html.zip -O input/refman56-html.zip
# 
# result=$?
# if [ $result -ne 0 ]; then
#     echo "[Error:$result] Failed to get http://mydocs.no.oracle.com/docs/refman-5.6/en/html.zip"
#     exit 1
# fi

echo "Creating DocLib databases..."
mkdir output

# Do not create MySQL full documentation
# python ./mysqldoclib.py --db=./output/mysqldoclib_full_56.sqlite --title="MySQL 5.6 Reference Manual" --file=./input/refman56-html.zip build-man
# 
# result=$?
# if [ $result -ne 0 ]; then
#     echo "[Error:$result] Failed build MySQL 5.6 Reference Manual"
#     exit 1
# fi

python ./mysqldoclib.py --db=./output/mysqldoclib.sqlite --title="MySQL Workbench 6.0 Reference Manual database" --file=./input/wb-html-guitools.zip build-man

result=$?
if [ $result -ne 0 ]; then
    echo "[Error:$result] Failed build MySQL Workbench 6.0 Reference Manual database"
    exit 1
fi

python ./mysqldoclib.py --db=./output/mysqldoclib_webui.sqlite build-webui

result=$?
if [ $result -ne 0 ]; then
    echo "[Error:$result] Failed build WebUI repository database"
    exit 1
fi

cp output/mysqldoclib.sqlite output/mysqldoclib_webui.sqlite ../res/DocLibrary

echo "Verifying documentation..."

if [ ! -f "../res/DocLibrary/mysqldoclib.sqlite" -o ! -f "../res/DocLibrary/mysqldoclib_webui.sqlite" ]; then 
  echo "Filed to validate that the result files exist."
  exit 1
fi

echo "Cleaning up..."

rm -rf input
rm -rf output

exit 0