#!/bin/sh
# -*- mode: shell-script; coding: utf-8 -*-
#
# reconfigure-package
#
# Script to reconfigure package without invoking dpkg-reconfigure(8),
# e.g. from within another maintainer script.
#
# Copyright (C) 2019 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
. /lib/elho/deb-tools

invoke_maintscript ()
{
    local package="$1"
    local maintscript="$2"
    local action="$3"
    local version="$4"

    local script="/var/lib/dpkg/info/${package}.${maintscript}"

    if [ -x "${script}" ]; then
	"${script}" "${action}" "${version}"
    fi
}


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

package="$1"

if ! package_installed "${package}"; then
    warn "Package '${package}' is not installed!"
    exit
fi

version="$(package_version "${package}")"

if [ -z "${version}" ]; then
    warn "Unable to determine package '${package}' version!"
    exit
fi

architecture="$(package_architecture "${package}")"

if [ -z "${architecture}" ]; then
    warn "Unable to determine package '${package}' architecture!"
    exit
fi

echo "Reconfiguring '${package}'..."
(
    export DPKG_MAINTSCRIPT_PACKAGE="${package}"
    export DPKG_MAINTSCRIPT_ARCH="${architecture}"
    export DPKG_MAINTSCRIPT_NAME="${maintscript}"

    export DEBCONF_RECONFIGURE=1

    invoke_maintscript "${package}" prerm upgrade "${version}"
    invoke_maintscript "${package}" config reconfigure "${version}"
    invoke_maintscript "${package}" postinst configure "${version}"
)
