@rem = '--*-Perl-*--
@echo off
if "%OS%" == "Windows_NT" goto WinNT
perl -x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9
goto endofperl
:WinNT
perl -x -S %0 %*
if NOT "%COMSPEC%" == "%SystemRoot%\system32\cmd.exe" goto endofperl
if %errorlevel% == 9009 echo You do not have Perl in your PATH.
if errorlevel 1 goto script_failed_so_exit_with_non_zero_val 2>nul
goto endofperl
@rem ';
#!/usr/bin/perl -w
#line 15

# Copyright (C) 2005, 2006 Apple Computer, Inc.  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1.  Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer. 
# 2.  Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution. 
# 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
#     its contributors may be used to endorse or promote products derived
#     from this software without specific prior written permission. 
#
# THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# "unpatch" script for Web Kit Open Source Project, used to remove patches.

# Differences from invoking "patch -p0 -R":
#
#   Handles added files (does a svn rm). 
#   Handles added directories (does a svn rm and a rmdir).
#   Handles removed files (does a svn revert). 
#   Handles removed directories (does a svn revert). 
#   Paths from Index: lines are used rather than the paths on the patch lines, which
#       makes patches generated by "cvs diff" work (increasingly unimportant since we
#       use Subversion now).
#   ChangeLog patches use --fuzz=3 to prevent rejects.
#   Handles binary files (requires patches made by svn-create-patch).
#
# Missing features:
#
#   Handle property changes.
#   Handle file moves (would require patches made by svn-create-patch).
#   Use version numbers in the patch file and do a 3-way merge.
#   When reversing an addition, check that the file matches what's being removed.
#   Notice a patch that's being unapplied at the "wrong level" and make it work anyway.
#   Do a dry run on the whole patch and don't do anything if part of the patch is
#       going to fail (probably too strict unless we exclude ChangeLog).

use strict;
use warnings;

use Cwd;
use File::Basename;
use File::Spec;
use Getopt::Long;
use FindBin qw($Bin);

sub patch($);
sub revertDirectories();
sub svnStatus($);
sub unapplyPatch($$;$);

my $showHelp = 0;
if (!GetOptions("help!" => \$showHelp) || $showHelp) {
    print STDERR basename($0) . " [-h|--help] patch1 [patch2 ...]\n";
    exit 1;
}

my $patch_cmd = "$Bin\\patch.exe";

my %directoriesToCheck;

my $indexPath;
my $patch;
while (<>) {
    s/\r//g;
    chomp;
    if (/^Index: (.*)/) {
        $indexPath = $1;
        if ($patch) {
            patch($patch);
            $patch = "";
        }
    }
    if ($indexPath) {
        # Fix paths on diff, ---, and +++ lines to match preceding Index: line.
        s/^--- \S+/--- $indexPath/;
        if (s/^\+\+\+ \S+/+++ $indexPath/) {
            $indexPath = "";
        }
    }
    $patch .= $_;
    $patch .= "\n";
}
patch($patch);

revertDirectories();

exit 0;

sub patch($)
{
    my ($patch) = @_;
    return if !$patch;

    $patch =~ m|^Index: ([^\n]+)| or die "Failed to find Index: in \"$patch\"\n";
    my $fullPath = $1;
    $directoriesToCheck{dirname($fullPath)} = 1;

    my $deletion = 0;
    my $addition = 0;
    my $isBinary = 0;

    $addition = 1 if $patch =~ /\n--- .+\(revision 0\)\n/;
    $deletion = 1 if $patch =~ /\n@@ .* \+0,0 @@/;
    $isBinary = 1 if $patch =~ /\nCannot display: file marked as a binary type\./;

    if (!$addition && !$deletion && !$isBinary) {
        # Standard patch, patch tool can handle this.
        if (basename($fullPath) eq "ChangeLog") {
            my $changeLogDotOrigExisted = -f "${fullPath}.orig";
            unapplyPatch($patch, $fullPath, ["--fuzz=3"]);
            unlink("${fullPath}.orig") if (! $changeLogDotOrigExisted);
        } else {
            unapplyPatch($patch, $fullPath);
        }
    } else {
        # Either a deletion, an addition or a binary change.

        # Reverse change by deleting current copy if it exists first
        unlink($fullPath) if (-e $fullPath);

        # Then run svn revert
        system "svn", "revert", $fullPath;
    }
}

sub revertDirectories()
{
    my %checkedDirectories;
    foreach my $path (reverse sort keys %directoriesToCheck) {
        my @dirs = File::Spec->splitdir($path);
        while (scalar @dirs) {
            my $dir = File::Spec->catdir(@dirs);
            pop(@dirs);
            next if (exists $checkedDirectories{$dir});
            if (-d $dir) {
                my $svnOutput = svnStatus($dir);
                if ($svnOutput && substr($svnOutput, 0, 1) eq "A") {
                   system "svn", "revert", $dir;
                   rmdir $dir;
                }
                elsif ($svnOutput && substr($svnOutput, 0, 1) eq "D") {
                   system "svn", "revert", $dir;
                }
                else {
                    # Modification
                    print $svnOutput if $svnOutput;
                }
                $checkedDirectories{$dir} = 1;
            }
            else {
                die "'$dir' is not a directory";
            }
        }
    }
}

sub svnStatus($)
{
    my ($fullPath) = @_;
    open SVN, "svn status --non-interactive --non-recursive $fullPath |" or die;
    my $svnStatus = <SVN>;
    close SVN;
    return $svnStatus;
}

sub unapplyPatch($$;$)
{
    my ($patch, $fullPath, $options) = @_;
    $options = [] if (! $options);
    my $command = "$patch_cmd " . join(" ", "-p0", "-R", @{$options});
    open PATCH, "| $command" or die "Failed to patch $fullPath\n";
    print PATCH $patch;
    close PATCH;
}

__END__
:endofperl
