#!/bin/sh -e

case $1 in
    "--apply")        
        ACTION=""
        ;;
    "--print")        
        ACTION="echo"
        ;;
     *)
        echo "Invokation: $0 --apply | --print" >/dev/stderr
        exit 1
        ;;
esac

ETC="/usr/local/etc/hs-debian-packages.conf"
CNF=$(tempfile)
SYS=$(tempfile)

DEBIAN_FRONTEND=noninteractive
HS_DISABLE_DAEMON_ACTION=yes

export DEBIAN_FRONTEND
export HS_DISABLE_DAEMON_ACTION

grep -v "#" $ETC |cut -d " " -f 1,2 >$CNF
dpkg -l |tail +6 |tr -s "[:space:]" |cut -d " " -f 2,3 >$SYS

diff $CNF $SYS |grep "^<" |cut -d " " -f 2,3 |while read DEB VER; do
    echo "$DEB=$VER"
done |xargs -r $ACTION apt-get --fix-broken --force-yes --option Dpkg::Options::='--force-confdef' --option Dpkg::Options::='--force-confold' --purge install

grep -v "#" $ETC |cut -d " " -f 1 >$CNF
dpkg -l |tail +6 |tr -s "[:space:]" |cut -d " " -f 2 >$SYS

diff $CNF $SYS |grep "^>" |cut -d " " -f 2 |while read DEB; do
    echo "$DEB"
done |xargs -r $ACTION apt-get --fix-broken --force-yes --option Dpkg::Options::='--force-confdef' --option Dpkg::Options::='--force-confold' --purge remove

rm $CNF $SYS
