#!/bin/sh
set -e

# update the lists
bin/update

# build list of required uris
fetch () {
    bin/each bin/fetch "-qq --print-uris $1" >> uris
}

rm -f uris
fetch "upgrade --force-yes"
fetch "dist-upgrade --force-yes"

# build a script to do wgets in parallel
cat > wgets <<EOF
function pau {
    NWGET=\`pgrep wget|wc --lines\`
    while test \$NWGET -gt 8; do
	sleep 1
        echo -n .
	NWGET=\`pgrep wget|wc --lines\`
    done
    wget --quiet --continue --background \$*
    BASE=\`basename \$2\`
    echo -e "\\r\$BASE begun"
}
EOF

sort uris | uniq | awk '{print "pau --output-document=" $2 " " $1}' >> wgets

echo pause
read ok

# build a place to put the stuff
mkdir -p tmp
cd tmp

. ../wgets

# wait for completion of all wgets
while pgrep wget > /dev/null; do
    sleep 1
    echo -n .
done
echo

# build list of md5's found
md5sum *.deb | sort > md5-found

# build list of md5's expected
sort ../uris | uniq | awk '{print $4 "  " $2}'|sort > md5-wanted

# compare the list, if equal move the files
diff md5-wanted md5-found && \
mv *.deb ../var/cache/apt/archives/ && \
rm wget-log* md5-found md5-wanted

# should be nothing left
ls
