#!/bin/sh

# we need a temp file to store already calculated dependencies
# otherwhise there is a risk of infinite recursion
TMP="/tmp/depend_graph"
rm -f $TMP

# location of graph (image and dot file)
GRAPH="/tmp"


# graphviz code
echo "digraph depend {" > $GRAPH/depend_graph.dot
# add default node style (similar to packages.debian.org)
echo "    node [shape=ellipse, color=black, fillcolor=firebrick1, style=filled];" >> $GRAPH/depend_graph.dot

# function for calculating dependency
depends()
{
 for dependency in $(apt-cache depends $1 | grep "Depends:" | cut -d ":" -f2)
 do
 	# add dependency to dot file
 	echo "    \"$1\" -> \"$dependency\";" >> $GRAPH/depend_graph.dot

	# have we already calculated the current dependency?
 	if ! grep -q "^$dependency$" $TMP
 	then
	 	echo $dependency >> $TMP
	 	# recursive call function depends()
 		depends $dependency
 	fi
 done
}

# function for calculating recommended and suggested package
rec_sug()
{
 apt-cache depends $1 | while read line
 do
 	if $(echo $line | grep -q "Recommends:")
 	then
 		dependency=$(echo $line | cut -d ":" -f2 | tr -d ' ')
 		# set node style (similar to packages.debian.org) and add recommended package to dot file
 		echo "    \"$dependency\" [shape=diamond, color=black, fillcolor=green, style=filled];" >> $GRAPH/depend_graph.dot
 		echo "    \"$1\" -> \"$dependency\";" >> $GRAPH/depend_graph.dot
 	elif $(echo $line | grep -q "Suggests:")
 	then
 		dependency=$(echo $line | cut -d ":" -f2 | tr -d ' ')
 		echo "    \"$dependency\" [shape=box, color=black, fillcolor=dodgerblue, style=filled];" >> $GRAPH/depend_graph.dot
 		echo "    \"$1\" -> \"$dependency\";" >> $GRAPH/depend_graph.dot
 	fi
 done
}


# call functions with first parameter (= packet name)
depends $1

rec_sug $1

# add final bracket
echo "}" >> $GRAPH/depend_graph.dot


# run dot (graphviz) do draw the graph
dot $GRAPH/depend_graph.dot -Tpng -o $GRAPH/depend_graph.png

