#!/bin/bash

if [ $# -ne 6 ];
then
    echo "usage: "$(basename $0) "[graph.vg] [graph.xg] [chunk_size] [context] [output_pdf] [dot|neato]"
    echo "requires vg, pdfunite (from pdftk) and dot (graphviz)"
    echo "first index the graph with `vg index -x ...` and then choose a chunk size"
    exit
fi

vg=$1
xg=$2
chunk=$3
context=$4
out=$5
renderer=$6

h=$(vg view $vg | grep ^S | cut -f 2 | sort -n | head -1)
t=$(vg view $vg | grep ^S | cut -f 2 | sort -n | tail -1)

echo "generating pdfs"
for i in $(seq $h $chunk $t);
do
    s=$i
    e=$(echo $i + $chunk | bc)
    echo "generating pdf for $s to $e"
    if [ "$renderer" == "neato" ];
    then
        vg find -x $xg -r $s:$e -c $context \
            | vg mod -z - \
            | vg view -dn - \
            | neato -Tpdf -o $out.tmp.$s
    elif [ "$renderer" == "mars" ];
    then
        vg find -x $xg -r $s:$e -c $context \
            | vg mod -z - \
            | vg view -dn - \
            | mars -g -k $chunk \
            | neato -Tpdf -n -o $out.tmp.$s
    elif [ "$renderer" == "marsnopath" ];
    then
        vg find -x $xg -r $s:$e -c $context \
            | vg mod -z - \
            | vg view -d - \
            | mars -g -k $chunk \
            | neato -Tpdf -n -o $out.tmp.$s
    elif [ "$renderer" == "marspath" ];
    then
         vg find -x $xg -r $s:$e -c $context \
            | vg mod -z - \
            | vg view -dpn - \
            | mars -g -k $chunk \
            | neato -Tpdf -n -o $out.tmp.$s
    elif [ "$renderer" == "marssimple" ];
    then
         vg find -x $xg -r $s:$e -c $context \
            | vg mod -z - \
            | vg view -dpS - \
            | mars -g -k $chunk \
            | neato -Tpdf -n -o $out.tmp.$s
    elif [ "$renderer" == "dot" ];
    then
        vg find -x $xg -r $s:$e -c $context \
            | vg mod -z - \
            | vg view -dpn - \
            | dot -Tpdf -o $out.tmp.$s
    elif [ "$renderer" == "dotnopath" ];
    then
         vg find -x $xg -r $s:$e -c $context \
             | vg mod -z - \
             | vg view -d - \
             | dot -Tpdf -o $out.tmp.$s
    elif [ "$renderer" == "dotnolabels" ];
    then
        vg find -x $xg -r $s:$e -c $context \
            | vg mod -u - \
            | vg mod -K - \
            | vg mod -cz - \
            | vg view -d - \
            | dot -Tpdf -o $out.tmp.$s
    fi
    #cairosvg $out.tmp.$s -fpdf -o $out.tmp.$s.pdf
    # also try mars if rendering is problematic
done

echo "combining pdfs"
pdfunite $(ls $out.tmp.* | sort -V) $out

echo "cleaning up"
rm $out.tmp.*
