#! /bin/bash
# Script to apply patches from qt-copy/patches/.
# See README.qt-copy for details.
#
# Lubos Lunak <l.lunak@kde.org>
#

if ! test -d patches; then
    echo No patches directory found.
    exit 1
fi

reverse=
test "x$1" = x-r -o "x$1" = x-R -o "x$1" = x--reverse && reverse=--reverse

patches=`cd patches/ >/dev/null && ls [0-9]*-* $reverse`
applied=
skipped=
for file in $patches; do
    # skip *~, *.sav, *.bak
    test "${file%\~}" != "$file" -o "${file%\.sav}" != "$file" -o "${file%\.bak}" != "$file" && continue
    # skip files that aren't *.diff or *.patch
    test "${file%\.patch}" = "$file" -a "${file%\.diff}" = "$file" && continue
    # apply only those having 'applied: no' in the header
    head -n 5 patches/$file | grep '^[\t ]*[Aa]pplied[\t ]*:[\t ]*[Nn][Oo][\t ]*$' >/dev/null || continue
    number=`echo $file | sed 's/^\([0-9]*\)-.*/\1/'`
    numsearch='^[\t ]*'"$number"'[\t ]*$'
    if grep "$numsearch" patches/DISABLED >/dev/null; then
        skipped="$skipped $file\n"
        continue; # disabled
    fi
    if true; then # for debugging
        echo -e "\nApplying: $file"
        if ! patch -p0 $reverse < patches/$file; then
            echo -e "\n\nPatch $file failed!"
            exit 1
        fi
    fi
    applied="$applied $file\n"
done

echo -e "\n\n\nDone.\n"
echo -e "Applied patches:\n$applied"
echo -e "Skipped patches:\n$skipped"

exit 0
