#!/bin/bash

#set -x

FILE=$1
PACKAGES=$2
# read $FILE using the file descriptors
exec 3<&0
exec 0<$FILE

while read src fromver tover; do

  mkdir -p /var/tmp/exp-$src
  dest=/var/tmp/exp-$src/$src

  #select all binary packages in with the given source
  grep-dctrl -e -F Package,Source "^$src( |\(| *$)" -a \
    -F Version "[0-9][0-9]*:$fromver.*$" -o \
    -X -F Version $fromver $PACKAGES > $dest-cluster

  grep-dctrl -e -F Package,Source "^$src( |\(| *$)" $PACKAGES | \
    grep-dctrl -v -F Version "[0-9][0-9]*:$fromver.*$" -o \
    -X -F Version $fromver > $dest-leftover

  #select all binary packages that have a different source
  grep-dctrl -e -v -F Package,Source "^$src( |\(| *$)" $PACKAGES > $dest-without

  #create the migration list $fromver -> $tover of the cluster
  #taking care of migrate packages with different epoch
  egrep -v 'Depends:|Conflicts:|Breaks:' $dest-cluster | sed \
    -e "s/Version: \([0-9][0-9]*:\)$fromver.*/Version: \1$tover/" \
    -e "s/Version: $fromver.*/Version: $tover/" > $dest-migration

  #echo "Before ..."
  #grep-dctrl -e -F Source "^$src( |\(| *$)" -s Package,Version,Source $dest-cluster

  #echo "After Upgrade"
  #grep-dctrl -e -F Source "^$src( |\(| *$)" -s Package,Version,Source $dest-migration

  #create the new universe to test
  cat $dest-without $dest-migration $dest-leftover > $dest-newuniv

  echo "check $src : $fromver -> $tover"
  #cat $dest-newuniv | edos-debcheck -failures
  ./distcheck.native deb://$dest-newuniv
  echo

done
exec 0<&3

echo "remember to remove all temporary files in /var/tmp/exp-*"
