#!/bin/bash

# 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.

BUILD_FAIL=0

function setup_directories {
    language=$1
    for directory in ${DIRECTORIES["$language"]} ; do
        echo "   $directory"
        openstack-generate-docbook -l $language -b $directory -r $DOC_DIR
    done
}


function setup_language {
    language=$1
    echo "Setting up files for $language"
    echo "======================="
    echo "  Directories:"
    setup_directories $language
    if [ -n "$POM_FILE" ] ; then
        cp $POM_FILE generated/$language/pom.xml
    fi
}


function test_language {
    language=$1

    echo
    echo "Building for language $language"
    echo

    setup_language $language

    args=("-v")
    if [[ $PURPOSE -eq "publish" ]]; then
        args+=("--publish")
    fi
    args+=("--check-build" "-l $language")
    for book in ${BOOKS["$language"]}; do
        args+=("--only-book $book")
    done

    openstack-doc-test ${args[@]}

    if [[ $? -eq 0 ]] ; then
        echo "... succeeded"
    else
        echo "... failed"
        BUILD_FAIL=1
    fi
}


function usage {
    echo "usage: $0 CONF_FILE PURPOSE LANGUAGE1 LANGUAGE2 ..."
    echo
    echo "CONF_FILE is the path to the configuration file."
    echo
    echo "PURPOSE is either 'test' or 'publish'."
    echo
    echo "LANGUAGE is either 'all' or 'LANG'."
    echo "LANG is a language code like 'fr' or 'ja'."
}


CONF_FILE=$1
shift

if [[ -z $CONF_FILE ]]; then
    usage
    exit 1
fi

if [[ ! -e $CONF_FILE ]]; then
    echo "Error: the configuration file '$CONF_FILE' does not exist"
    exit 1
fi

source $CONF_FILE

if [[ -z $(declare -p BOOKS 2> /dev/null | grep 'declare -A BOOKS') || \
      -z $(declare -p DIRECTORIES 2> /dev/null | grep 'declare -A DIRECTORIES') || \
    -z $DOC_DIR ]]; then
    echo "Error: the configuration file '$CONF_FILE' is invalid"
    exit 1
fi

case "$1" in
    test|publish)
        PURPOSE=$1
        shift
        ;;
    *)
        usage
        exit 1
        ;;
esac

for language in "$@" ; do
    case "$language" in
        all)
            for language in "${!BOOKS[@]}"; do
                test_language $language
            done
            ;;
        *)
            if [[ -n ${BOOKS[$language]} ]]; then
                test_language $language
            else
                BUILD_FAIL=1
                echo "Error: language $language not handled"
            fi
            ;;
    esac
done

exit $BUILD_FAIL
