#!/bin/sh
# DocumentId:	$Id: dpsyco-applypatch 2410 2007-03-21 12:17:27Z ola $
# Author:	$Author: ola $
#		Ola Lundqvist <opal@debian.org>
# Date:		$Date: 2007-03-21 13:17:27 +0100 (Wed, 21 Mar 2007) $
# Arguments:	$1	Patch file.
#		$2	Destination.
#    (optional) $3	Extra patch options.
# Summary:
#	Patches a file structure.
#
# Copyright (C) 2001-2004 Ola Lundqvist <opal@debian.org>
#
# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
#

PF="$1"
DESTR="$2"
PATCHOPT="$3"

if [ -z "$PF" ] ; then
    echo "No patch file specified, exiting."
    exit 0
fi
if [ -z "$DESTR" ] ; then
    echo "No destination specified, exiting."
    exit 0
fi

DEST=$(echo "$DESTR" | sed -e "s|/$||;")

TF=/var/lib/dpsyco-patch/tmp

if [ ! -f $PF ] ; then
    echo "Can not find patch file $PF."
else
    FILES=$(grep "^+++ " $PF | sed -e "s|^+++ ||" | sed "s|[[:space:]].*||")
    if [ -e $TF ] ; then
	rm -f $TF
    fi
    echo "#\!/bin/sh" > $TF
    for FILE in $FILES ; do
	find "$DEST/$FILE" -prune -printf "chown %u.%g %p\nchmod %m %p\n" >> $TF
    done
    patch -d $DESTR $PATCHOPT -s -f -T -p0 < $PF
    if [ -e $TF ] ; then
	chmod +x $TF
	$TF
	rm -f $TF
    fi
fi
