#!/bin/sh

##
# Copyright (c) 2005-2007 Apple Inc. All rights reserved.
#
# 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 -e
set -u

 wd="$(cd "$(dirname "$0")" && pwd -P)";
top="$(cd "${wd}/../../.." && pwd -L)"

export PYTHONPATH="$("${wd}/../../run" -p)";

##
# Download and set up dependancies
##

epydoc="${top}/epydoc-2.1";

if [ ! -d "${epydoc}" ]; then
   echo "Downloading Epydoc...";
   cd "${top}" && curl http://easynews.dl.sourceforge.net/sourceforge/epydoc/epydoc-2.1.tar.gz | tar xvzf -;
fi;

if [ ! -d "${epydoc}/build/lib" ]; then
   cd "${epydoc}" && python ./setup.py build;
fi;

pydoctor="${top}/pydoctor";

if [ ! -d "${pydoctor}" ]; then
    echo "Downloading PyDoctor...";
    cd "${top}" && svn co http://codespeak.net/svn/user/mwh/pydoctor/trunk pydoctor;
fi;

if [ ! -d "${pydoctor}/build/lib" ]; then
   cd "${pydoctor}" && python ./setup.py build;
fi;

nevow="${top}/Nevow";
if [ ! -d "${nevow}" ]; then
    echo "Downloading Nevow...";
    cd "${top}" && svn co http://divmod.org/svn/Divmod/trunk/Nevow;
fi;

export PYTHONPATH="${PYTHONPATH}:${epydoc}/build/lib:${pydoctor}/build/lib/:${nevow}";

python_version="$(python -V 2>&1)";
python_version="${python_version#Python }";
python_version="${python_version%*.*}";

pydoctor="${pydoctor}/build/scripts-${python_version}/pydoctor";

cd "${wd}";

if [ ! -f "${top}/twisted.pickle" ]; then
    echo "Generating Twisted documentation...";
    "${pydoctor}" -c twisted.cfg -o "${top}/twisted.pickle";
fi;

##
# Generate documentation
##

echo "Generating TwistedCalDAV documentation...";
"${pydoctor}" -c twistedcaldav.cfg --resolve-aliases --extra-system="${top}/twisted.pickle:http://twistedmatrix.com/documents/current/api/" --make-html;
