#! /bin/sh -e
#
# Copyright 2014  Aurélien Gâteau <agateau@kde.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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
