#! /bin/sh -e
#
# SPDX-FileCopyrightText: 2014 Aurélien Gâteau <agateau@kde.org>
#
# SPDX-License-Identifier: BSD-2-Clause

oldpwd=$PWD
cd "$(dirname "$0")"
bindir=$PWD
cd "$oldpwd"
generate=$bindir/depdiagram-generate

die() {
    echo "$*" 1>&2
    exit 1
}

if [ ! -x "$generate" ] ; then
    die "Can not find the depdiagram-generate script"
fi

if [ "$#" -ne 2 ] ; then
    die "Usage: $(basename "$0") <dot_dir> <png_dir>"
fi

dot_dir=$1
png_dir=$2

if [ ! -d "$dot_dir" ] ; then
    die "'$dot_dir' is not a directory"
fi

read_tier() {
    sed --quiet '/tier:/s/tier: *//p' "$1"
}

gen_fws() {
    tmp_dot=/tmp/diagram.dot

    for fw_dot in $fw_dots ; do
        fw=$(basename "$fw_dot" .dot)
        echo "$fw"

        # Gather info
        tier=$(read_tier "$(echo "$fw_dot" | sed 's/dot$/yaml/')")
        if [ "$tier" -lt 3 ] ; then
            opts=--qt
        else
            opts=""
        fi

        # Generate .dot file
        $generate "$fw_dots" --framework "$fw" "$opts" > $tmp_dot

        # Turn .dot into a .png
        dot -Tpng $tmp_dot > "$png_dir"/"$fw".png

        # Simplify .dot and turn it into a .png
        tred $tmp_dot | dot -Tpng > "$png_dir"/"$fw"-simplified.png
    done

    rm $tmp_dot
}

mkdir -p "$png_dir"

fw_dots=$(find "$dot_dir" -name '*.dot')

gen_fws

echo "kf5"
$generate "$fw_dots" | tred | dot -Tpng > "$png_dir"/kf5.png
