#!/bin/sh
#
# /usr/local/sbin/localbackuppkglists
# Copyright 2007 Jonas Smedegaard <dr@jones.dk>
#
# $Id: localbackuppkglists,v 1.3 2008-02-08 20:59:57 jonas Exp $
#
# Depends: aptitude and debconf-utils
#
# TODO: Use aptitude-create-state-bundle if available
# TODO: Mimic aptitude-create-state-bundle if not available
# TODO: Save packages recommended but unavailable

set -e

PRG=$(basename "$0")

TEMP="`getopt -s sh -o t:f -l target:,force -n "$PRG" -- "$@"`"
if [ $? != 0 ] ; then echo >&2 "ERROR: Internal getopt error." ; exit 1 ; fi
eval set -- "$TEMP"

targetdir=''
force='no'
while true ; do
	case "$1" in
		-t|--target) targetdir="$2" ; shift 2 ;;
		-f|--force) force="yes" ; shift ;;
		--) shift ; break ;;
		*) echo >&2 "ERROR: Internal error resolving options." ; exit 1 ;;
	esac
done

if [ -n "$targetdir" ]; then
	targetdirparent="$(dirname "$targetdir")"
	if ! [ -d "$targetdirparent" ]; then
		if [ "$force" = "yes" ]; then
			mkdir -p "$targetdirparent"
		else
			echo >&2 "Error: Parent directory for target directory does not exist."
			exit 1
		fi
	elif [ -e "$targetdir" ]; then
		if [ "$force" = "yes" ]; then
			rm -rf "$targetdir"
		else
			echo >&2 "Error: Target directory already exists."
			exit 1
		fi
	fi
fi

tempdir="$(mktemp -td localpkglists.XXXXXX)"

origlang="$LANG"
LANG='C'

dpkg --get-selections > "$tempdir/dpkg-selections.txt"

aptitude -F '%p#%v#' search '~i!~M' > "$tempdir/aptitude-installed-explicitly.txt"
aptitude -F '%p#%v#' search '~i!~Odebian' > "$tempdir/aptitude-installed-aliens.txt"
aptitude -F '%p#' search '!~i~Rrecommends:(~i)' > "$tempdir/aptitude-notinstalled-recommended.txt"

debconf-get-selections > "$tempdir/debconf-questions.txt"
debconf-get-selections --installer > "$tempdir/debconf-questions-di.txt" 2> /dev/null || true

LANG="$origlang"

if [ -n "$targetdir" ]; then
	mv "$tempdir" "$targetdir"
	rm -rf "$tempdir"
fi