#!/bin/bash
DB=binsize.db

cd `dirname $0`
for what in bin ram; do
    printf "Generating %s graph\n" "$what"
    (
        if [ "$what" == "bin" ]; then
            title="Binary size"
            max=1000000
        else
            title="RAM usage"
            max=5000000
        fi
        font="DejaVuSans"
#        printf 'set terminal png notransparent truecolor font "%s" 10 size 1024,768 x000000 x000000 xff0000\n' "$font"
        printf 'set terminal png notransparent truecolor font "%s" 10 size 1024,768\n' "$font"
        printf 'set title "%s" font "%s,20"\n' "$title" "$font"
        printf 'set xtics autofreq 0 2000\n'
#        printf 'set ytics autofreq 0 100\n'
        printf 'set mxtics 10\n'
        printf 'set mytics 5\n'
        printf 'set style line 40 linetype 1 linecolor rgb "#999999"\n'
        printf 'set style line 41 linetype 6 linecolor rgb "#DDDDDD"\n'
        printf 'set grid xtics ytics mxtics mytics linestyle 40 linestyle 41\n'
        printf 'set key left top\n'
        printf 'set key box\n'
        printf 'set xlabel "SVN revision"\n'
        printf 'set ylabel "Size in kilobytes"\n'
        printf 'set xrange [0:]\n'
        printf 'set yrange [0:]\n'
        printf 'plot '
    ) > $what.gnuplot

    foo="no"
    for target in `sqlite3 binsize.db "select distinct(target) as target from targets order by min(firstrev)" |grep -v "resources"`; do
        if [ "$foo" = "no" ]; then
            foo="yes"
        else
            printf ", \\\\\n     " >> $what.gnuplot
        fi

        if [ "$what" == "bin" ]; then
            max=1000000
        else
            max=5000000
        fi

        echo "  $target"
        sqlite3 -separator "	" $DB "SELECT revision, $what/1000 FROM binsizes WHERE target='$target' AND $what BETWEEN -1 AND $max AND binsizes.bin<binsizes.ram+100000 ORDER BY revision"|grep -v "Loading resources"| sed 's/^.*\t0$//' > $what-$target.dat
        printf '"%s" using 1:2 with lines title "%s"' $what-$target.dat "$target" >> $what.gnuplot
    done
    GDFONTPATH=/usr/share/fonts/truetype/ttf-dejavu gnuplot -background white $what.gnuplot > $what.png
done
