#!/bin/sh

unset TMP new newpkgs line

quit() {
    rm -rf $TMP
    exit $@
}

trap 'echo "Killed by signal"; quit 2' INT TERM
TMP=`mktemp -d` || quit 1

# list of installed, (still) available pkgs
LANG=C slapt-get --available | grep 'inst=yes' | awk '{ print $1 }' >$TMP/reinst

if egrep -q '^ *$' $TMP/reinst; then
    echo "Nothing to install"
    quit
fi

# missing deps will be listed as new pkgs
if ! LANG=C slapt-get -s --reinstall -i $(cat $TMP/reinst) >$TMP/sget && \
        ! egrep -q "^You don't have enough free space in " $TMP/sget; then
    quit 1
fi

# extract new pkgs
while read line; do
    if echo $line | egrep -q "^The following .*packages will be"; then
        new="false"
    fi
    if [ "x$new" == "xtrue" ]; then 
        newpkgs="$newpkgs$line "
    fi
    if [ "x$line" == "xThe following NEW packages will be installed:" ]; then
        new="true"
    fi
done <$TMP/sget

if echo "$newpkgs" | egrep -q '^ *$'; then
    echo "Nothing to install"
    quit
fi

# install new pkgs (i.e. missing deps)
slapt-get -p -i $newpkgs || quit 1

quit

