#!/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,2011 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

. /lib/elho/shell-tools

package_installed ()
{
    local package="$1"

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

preseed_to_configdb ()
{
    local file="$1"
    local package="$2"

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

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

preseedfile="$1"

if [ -z "${preseedfile}" ]; then
    preseedfile=$(mktemp -t "$(basename "$0")-dd-XXXXXX")
    add_trap "rm -f \"${dd_output}\"" EXIT

    cat - > "${preseedfile}"
else
    if [ ! -f "${preseedfile}" ]; then
	error "Preseed file '${preseedfile}' does not exist!"
	exit 1
    fi
fi

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
