#!/bin/sh
# -*- mode: shell-script; coding: utf-8 -*-
#
# customize-conffile
#
# Script to customize a configuration file using a given sed(1) script.
#
# Copyright (C) 2010-2012 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

PATCHDIR='/usr/share/elho/customize'

distmd5sum ()
{
    if [ "${debug}" -eq 1 ]; then
	/lib/elho/distmd5sum --debug "$@"
    else
	/lib/elho/distmd5sum "$@"
    fi
}

usage ()
{
    echo "Usage: $(basename "$0") [--debug] [--ok] FILE"
}

set +e
commandline=$(getopt --name "$(basename "$0"): Error" \
    --options='?hd' --longoptions='help,usage,debug,ok' -- "$@")
if [ $? -ne 0 ]; then
    usage
    exit 2
fi
set -e
eval set -- "${commandline}"
debug=0
status_ok=0
while true; do
    case "$1" in
        -\?|-h|--help|--usage)
            usage
            exit
            ;;
        -d|--debug)
            debug=1
            ;;
        --ok)
            status_ok=1
            ;;
        --)
            shift
            break
            ;;
        *)
            error "Invalid getopt(1) output."
            exit 1
            ;;
    esac
    shift
done
if [ $# -ne 1 ]; then
    usage
    exit 2
fi

file=$(readlink --canonicalize-missing "$1")

if [ "${debug}" -eq 1 ]; then
    enable_verbose
    enable_debug
fi

script="${PATCHDIR}${file}.sed"

if [ ! -e "${file}" ]; then
    error "Can not customize '${file}': No such file or directory"
    exit 1
fi

if [ ! -e "${script}" ]; then
    error "Can not customize '${file}': No customization script available"
    exit 1
fi

echo -n "Customizing '${file}'..."
status=1
if ! sed --file="${script}" "${file}" \
    | diff --brief "${file}" - > /dev/null; then
    if distmd5sum "${file}"; then
	extension='.dpkg-dist'
    else
	extension='.dpkg-old'
    fi
    sed --in-place="${extension}" --file="${script}" "${file}"
    echo " done."
    debug "Original version preserved as '${file}${extension}'."
    status=0
else
    echo " no changes necessary."
fi

if [ "${status_ok}" -eq 1 ]; then
    if [ "${debug}" -eq 1  -a "${status}" -ne 0 ]; then
	debug "Suppressing exit status ${status}."
    fi
    exit 0
else
    exit "${status}"
fi