#!/bin/sh

# at2quilt
# Copyright (c) 2011, Frank Terbeck <ft@bewatermyfriend.org>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# This script automates the task of creating quilt patches for debian's
# zsh package for generating autotools files, which are otherwise created
# by calling `./Utils/preconfig'.
#
# Here is how this script fits into the packages release workflow:
#   Everytime an update to the autotools files is needed (usually after
#   an upstream release) this script should be called in an otherwise
#   clean git repository. After the script ran, all autotools related
#   git patches should be updated, ready for commit. The final commit
#   is not done automatically to give the caller the chance of catching
#   undesired behaviour.
#
# This script creates these patches:
#   - deb_at_configure.diff
#   - deb_at_config_h_in.diff
#
# `preconfig' also creates another file `stamp-h.in', which is empty. The
# build process (aka. debian/rules) should just touch(1) that file early.
#
# Note: Call this script *only* from the git repository's base directory.

QUILT_PATCHES=debian/patches
export QUILT_PATCHES
INDEX=${PWD##*/}
INDEX=${INDEX%/}

if ! quilt --version > /dev/null 2>&1; then
    printf 'Ooops, `quilt(1)'\'' not found. Giving up.\n'
    exit 1
fi

if [ ! -d "${QUILT_PATCHES}" ]; then
    printf 'No such directory: `%s'\''\n' "${QUILT_PATCHES}"
    printf 'Quilt patches directory not found. Giving up.\n'
    exit 1
fi

printf 'Cleaning up...\n'

# Unapply everything
quilt pop -a

# Manually apply the patches from the command line, so we can have
# changes to configure.ac etc.
for patch in "$@"; do
    patch -p1 < "${patch}" || {
        printf 'Aarrgh! Manually applying `%s'\'' failed. Giving up.\n' "${patch}"
        exit 1
    }
    # Keep reverse order for later.
    if [ "x${PATCHES}" = x ]; then
        PATCHES=${patch}
    else
        PATCHES="${patch} ${PATCHES}"
    fi
done

# Clean up old files that may be around.
rm -f configure config.h.in stamp-h.in
rm -Rf autom4te.cache

# Now let `preconfig' do its magic, so we end up with fresh files.
printf '\nRunning `preconfig'\''\n'
if ! ./Util/preconfig; then
    printf '\nOops, `preconfig'\'' signaled an error. Giving up.\n'
    exit 1
fi
rm -Rf autom4te.cache

create_patch() {
    patch="${QUILT_PATCHES}/$1"
    file=$2
    series="${QUILT_PATCHES}/series"

    if [ ! -e "${file}" ]; then
        printf 'Target file `%s'\'' does not exist. Giving up.\n' "${file}"
        return 1
    fi

    cat << __EOF__ > "${patch}"
Patch to generate \`${file}'.

Created by \`at2quilt' on $(date +"%a, %d %b %Y %H:%M:%S %Z").

Note: Never *ever* refresh this patch. Things will break.

Index: ${INDEX}/${file}
__EOF__
    diff -u /dev/null "${file}" \
    | sed -e "1s,/dev/null,${INDEX}.orig/${file}," \
          -e "2s,^+++ [^[:space:]]*,+++ ${INDEX}/${file}," >> "${patch}"

    if ! grep -q '^'"$1"'$' "${series}"; then
        printf '`%s'\'' missing in `%s'\''. Adding.\n' "$1" "${series}"
        printf '%s\n' "$1" >> "${series}"
    fi
    return 0
}

create_patch deb_0000_at_configure.diff configure || exit 1
create_patch deb_0001_at_config_h_in.diff config.h.in || exit 1

# Clean up manually applied patches again, if any.
if [ "x${PATCHES}" != x ]; then
    for patch in ${PATCHES}; do
        patch -p1 -R < "${patch}" || {
            printf 'Aarrgh! Manually reverting `%s'\'' failed. Giving up.\n' "${patch}"
            exit 1
        }
    done
fi

# Try to push the entire current quilt series (this really shouldn't fail).
if ! quilt push -a; then
    printf 'Pushing the quilt series failed. Please investigate.\n'
    exit 1
fi

# Pop everything again.
if ! quilt pop -a; then
    printf 'Popping the quilt series failed. Please investigate.\n'
    exit 1
fi

printf 'Looks like everything went as expected.\n'
printf 'The autotools related patches in `%s'\'' should be up-to-date now.\n' \
    "${QUILT_PATCHES}"
printf 'To test the patches, do this:\n'
printf '  %% quilt push -a\n'
printf '  %% chmod 0755 configure\n'
printf '  %% ./configure\n'
printf '\nDo not forget to commit the updated patches to the git repository.\n'
exit 0
