#!/bin/bash

CWD=$PWD

# --- Config

source ./export.cfg

# --- Requirements

NEEDED_BINS="svn python curl meinproc4 advpng"
missing_bins=""
for needed_bin in $NEEDED_BINS; do
    if [ ! `which $needed_bin` ]; then
        missing_bins="$missing_bins$needed_bin "
    fi
done
if [ "$missing_bins" != "" ]; then
    echo "Missing binaries: $missing_bins"
    exit 1
fi

# --- main()

rm -rf doc
mkdir doc

if [ ! -d tooling ]; then
    svn checkout --depth=files svn://anonsvn.kde.org/home/kde/branches/work/doc/ tooling
else
    cd tooling
    svn up
fi

available_languages=""
for lang in $LANGS; do
    echo $lang
    lang_pages=""
    for page in $PAGES; do
        if [ $lang == "en" ]; then
            lang_pages="$lang_pages$page%0D%0A"
        else
            lang_pages="$lang_pages$page%2F$lang%0D%0A"
        fi
    done
    cd $CWD/doc
    rm -rf $lang
    mkdir $lang
    cd $lang
    curl \
    --silent \
    --remote-header-name \
    --data "catname=&pages=${lang_pages}&curonly=1&wpDownload=1" \
    --output index.xml \
    "https://userbase.kde.org/index.php?title=Special:Export&action=submit"
    python $CWD/tooling/wiki2docbook.py -r index.docbook index.xml &> /dev/null
    mv index.xml.new.docbook index.docbook
    rm -f index.xml
    export_valid=1
    if [ -f index.docbook ]; then
        mkdir tmp
        cp -rf * tmp &> /dev/null
        cd tmp
        if `meinproc4 --check index.docbook &> /dev/null`; then
            export_valid=0
         else
            echo "  docbook not valid"
        fi
        cd ..
        rm -rf tmp
    fi
    if [ $export_valid == 0 ]; then
        echo "kdoctools_create_handbook(index.docbook INSTALL_DESTINATION \${HTML_INSTALL_DIR}/$lang SUBDIR kubuntu)" > CMakeLists.txt
        available_languages="$available_languages $lang"
    else # Else the export failed, so drop all remaining parts.
        echo "  skip"
        cd $CWD/doc
        rm -rf $lang
    fi
done

cd $CWD/doc
rm -rf CMakeLists.txt
touch CMakeLists.txt
for available_language in $available_languages; do
    echo "add_subdirectory($available_language)" >> CMakeLists.txt
done

exit 0
