#!/bin/bash

get-ext-name() {
    sed -n -e '/^EXTENSIONNAME/{' -e 's/.*:=\s*//p' -e '}' $1/makefile.mk
}

collect-files() {
    find -L "$1" -mindepth 1 -maxdepth 1 -type f \
        \( -name delzip -o -name '*.dat' -o -name '*.xml' -o -name '*.mk' -prune \) \
        -o -print \
    | sort
}

print-header() {
cat <<'EOH'
# -*- Mode: makefile-gmake; tab-width: 4; indent-tabs-mode: t -*-
#
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#

EOH
}

print-footer() {
cat <<'EOF'

# vim: set noet sw=4 ts=4:
EOF
}

print-makefile() {
    local dir="$1"
    local name="$2"

    print-header

    echo "\$(eval \$(call gb_Dictionary_Dictionary,${name},${dir}))"
    echo

    echo "\$(eval \$(call gb_Dictionary_add_root_files,${name},\\"
    local file
    for file in $(collect-files "${dir}"); do
        echo -e "\t${file} \\"
    done
    echo '))'

    local thesauri="$(find -L "${dir}" -type f -name '*.dat' -print | sort)"
    if [[ -n ${thesauri} ]]; then
        echo
        echo "\$(eval \$(call gb_Dictionary_add_thesauri,${name},\\"
        for thesaurus in ${thesauri}; do
            echo -e "\t${thesaurus} \\"
        done
        echo '))'
    fi

    print-footer
}

create-makefile() {
    local dir="$1"
    local name="$(get-ext-name "$1")"
    local makefile="${dir%%/*}"/Dictionary_${name#dict-}.mk

    print-makefile "${dir}" "${name}" > "${makefile}"
}

create-makefiles() {
    local dir="$1"
    local makefile
    for makefile in $(find -L "${dir}" -name makefile.mk -print); do
        create-makefile "${makefile%/*}"
    done
}

create-makefiles dictionaries

# vim: set ts=4 sw=4 et:
