#!/bin/sh

if [ ! -n "$1" ]; then
  echo "Specify at least one package"
  exit 1
fi

doexit()
{
#tidy up tmp files
test -e "${TMPDIR}/${NAME}" && rm "${TMPDIR}/${NAME}"
test -d "${WORKDIR}" && rm -rf "${WORKDIR}"
exit $1
}

PACKAGES="$@"
NAME=$1


OUTPUTDIR=results
mkdir -p ${OUTPUTDIR}

WORKDIR=`mktemp -d findcycles.XXX`
echo "Calculating cyclic build-dependencies for $PACKAGES, results saved as $NAME"
xdeb.py -a armel --generate-graph --apt-source "$PACKAGES" | sccmap > "${WORKDIR}/${NAME}"
DIRSIZE=`wc ${WORKDIR}/${NAME} | awk '{print $1}'`
if [ "${DIRSIZE}" -eq "2" ] ; then 
  echo "No cyclic build-dependencies found"
  doexit 0
fi

echo "Generating graphs from dependencies: ${OUTPUTDIR}/$NAME.cycle"
cat "${WORKDIR}/${NAME}" | gvpr -f make_strict.g \
 | gvpr -f colour_nodes.g > "${OUTPUTDIR}/${NAME}.cycle"
 
echo "Creating images of graphs"
cat "${OUTPUTDIR}/${NAME}.cycle" | dot -Tps | sed "s/merge$/${NAME} build-dependency graph/" > "${OUTPUTDIR}/${NAME}.ps"
#In principle we could burst the .ps files into one ps or pdf per graph
#But I can't get it so they all fit on page _and_ aren't tiny.
#ps2ps "${WORKDIR}/${NAME}.ps" "${WORKDIR}/${NAME}%01d.ps"

#for file in ${WORKDIR}/${NAME}?.ps
#do 
#  filebase=`basename $file .ps`
#  echo "Generating ${OUTPUTDIR}/${filebase}.pdf" 
#  ps2epsi $file "${WORKDIR}/${filebase}.epsi"
#  cat "${WORKDIR}/${filebase}.epsi" | epstopdf --filter --exact --outfile="${OUTPUTDIR}/${filebase}.pdf"
#done

doexit 0
