#! /bin/sh

export DEBIAN_FRONTEND=noninteractive
set -e

if [ ! -r /etc/pkgsync/musthave -o \
     ! -r /etc/pkgsync/mayhave -o \
     ! -r /etc/pkgsync/maynothave ]; then
	echo Error: Missing files in /etc/pkgsync. Aborting.
	echo 
	echo Please see /usr/share/doc/pkgsync/README.Debian for information on 
	echo configuring pkgsync.
	
	exit 1
fi

readpkgs () {
	/bin/grep -vE '^#' "$1" | /bin/grep -vE '^\s*$' || /bin/true
}
getpkgs () {
	for pkg in $( readpkgs $1 ); do
		# if there's a wildcard (that is, [], * or ?) in this,
		# push it through dpkg-query to glob. if not, just print
		# it out.
		if echo "$pkg" | grep -Eq '[][*?]'; then
			/usr/bin/dpkg-query --showformat '${Package}\n' -W "$pkg" 2>/dev/null || /bin/true
		else
			echo "$pkg"
		fi
	done
}
run_aptitude () {
	echo RUNNING: aptitude -y "$@"
	/usr/bin/aptitude -y "$@" 
}
run_aptitude_if_nonempty () {
	if [ "$2" ]; then
		echo RUNNING: aptitude -y "$@"
		/usr/bin/aptitude -y "$@"
	fi
}

# The beautiful look of hacks in the morning...
filter () { 
	echo "$@" | /usr/bin/tr " " "\n" | /usr/bin/sort | /usr/bin/uniq -c | /bin/grep "     2" | /usr/bin/cut -c9-
}

# Update the package lists
run_aptitude update
/usr/bin/dselect update

# Find installed packages
installed=$( COLUMNS=5000 /usr/bin/dpkg -l | /bin/grep '^ii' | /usr/bin/cut -c5- | /usr/bin/cut '-d ' -f1 )
musthave=$( getpkgs /etc/pkgsync/musthave )
mayhave=$( getpkgs /etc/pkgsync/mayhave )
mustnothave=$( getpkgs /etc/pkgsync/maynothave )

# First of all, mark all packages we want (and have) as manually installed
run_aptitude_if_nonempty unmarkauto $( filter $installed $musthave $mayhave )

# Remove all packages from our `must not have' list
toremove=$( filter $installed $mustnothave )
run_aptitude_if_nonempty remove $toremove

# Add all packages from our `must have' list
toinstall=$( filter $musthave $musthave $installed )
run_aptitude_if_nonempty install $toinstall

# Update the list of installed packages
installed=$( COLUMNS=5000 /usr/bin/dpkg -l | /bin/grep '^ii' | /usr/bin/cut -c5- | /usr/bin/cut '-d ' -f1 )

# Now mark all packages we must or may have as manual, and the rest as
# automatically installed
run_aptitude_if_nonempty unmarkauto $( filter $installed $musthave $mayhave )
run_aptitude_if_nonempty markauto $( filter $installed $installed $musthave $mayhave )

# Make aptitude clean up
run_aptitude dist-upgrade
run_aptitude autoclean
