#!/bin/sh
# -*- mode: shell-script; coding: utf-8 -*-
#
# debconf-force-selections
#
# Script to update debconf values of installed packages from a preseed
# file.
#
# Copyright (C) 2010 Elmar Hoffmann
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

set -e

function package_installed () {
    dpkg-query --showformat='${Status}\n' --show "${1}" 2>/dev/null \
	| grep --quiet '^[^[:space:]]\+[[:space:]]\+ok[[:space:]]\+installed$'
}

function preseed_to_configdb () {
    sed --quiet --expression="s,^${2}[[:space:]]\+\([^[:space:]]\+\)[[:space:]]\+[^[:space:]]\+[[:space:]]\+\(.\+\)\$,Name: \1\nTemplate: \1\nValue: \2\\n,p" "${1}"
}

if [ $# -ne 1 ]; then
    echo "Usage: $(basename "$0") FILE"
    exit 2
fi

preseedfile="$1"

PACKAGENAME='[a-z0-9][a-z0-9.+-]\+'
packages=$(sed --quiet --expression="s/^\(${PACKAGENAME}\).*\$/\1/p" \
    "${preseedfile}" | sort --unique)
for package in ${packages}; do
    echo -n "Setting debconf values for '${package}'... "
    if package_installed "${package}"; then
	preseed_to_configdb "${preseedfile}" "${package}" \
	    | debconf-copydb --config='Name:stdin' --config='Driver:Pipe' \
	    --config='OutFd:none' stdin  configdb
	echo "done."
    else
	echo "not installed."
    fi
done
