#!/bin/sh  
# 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

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