#!/usr/bin/perl

# Copyright (c) 2007 Motorola, Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation.
#
# 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.

use strict;
use warnings FATAL => 'all';

sub error {
    my $msg = shift;

    print "Error: $msg\n";
    exit 1;
}

sub system_check {
    my $command = shift;

    if (system($command)) {
        error("$command failed");
    }
}

my $filename = shift or die "Error: Need a patch file";
my $arg2 = shift;
my $depmode = 0;
my $dir = ".";
if (defined($arg2)) {
    if ($arg2 eq "-dep-") {
        $depmode = 1;
    }
    else {
        $dir = $arg2;
    }
}

open(PATCH, "<$filename") or die "Error: Could not open patch file: $filename: $!";
while (<PATCH>) {
    next if /^#/;
    if (/(\S+)\s*(.*)/) {
        if ($depmode) {
            print "$1 ";
        }
        else {
            my $arg = $2 || "-p1";
            print "=== Applying $1 ===\n";
            system_check("patch -d $dir $arg < $1");
        }
    }
}
close PATCH;
if ($depmode) {
    print "$filename\n";
}
