#!/usr/bin/perl
#
# Splits a patch created with diff into separate patches and places
# the new patches into a directory structure. Licensed under GPL.
#
# Version 20040303-2
#
# Copyright (C) 2002 - 2004 Tony Lindgren <tony@atomide.com>
#
use strict;
use File::Path;

my($arg1, $patch_file, $tag) = @ARGV;

my $recursive = 0;

if ($arg1 eq "") {
    printf("Usage: %s [-r] patchfile_to_split\n", $0);
}

if ($arg1 eq "-r") {
    $recursive = 1;
} else {
    $patch_file = $arg1; 
}

my $new_patch_start = "diff -Nru";
my $delimiter = "/";
my $tag_name = "tagged";
my $debug = 0;

my $new_patch_path = "";
my $new_patch_name = "";
my $patch_path = "";
my $patch_name = "";
my $new_patch = "";

open IN, "<$patch_file"
    or die "Unable to read input file: $!";

while (<IN>) {
    if (/$new_patch_start/) {
        $patch_path = $new_patch_path;
        $patch_name = $new_patch_name;
        ($new_patch_path, $new_patch_name) = get_patch_path_and_name($_);
        if ($new_patch ne "") {
            create_new_patch($patch_path, $patch_name, $new_patch, $recursive);
            if ($debug gt 0) {
                printf(STDERR "Path: %s Patch: %s\n\n%s\n\n\n",
                       $patch_path, $patch_name, $new_patch);
            }
        }
        $new_patch = $_;
    } else {
        # Just keep appending until the tag is found
        $new_patch = $new_patch.$_;
    }
}

# Write out the last patch too
if ($new_patch ne "") {
    create_new_patch($new_patch_path, $new_patch_name, $new_patch, $recursive);
        if ($debug gt 0) {
            printf(STDERR "Path: %s Patch: %s\n\n%s\n\n\n",
                   $patch_path, $patch_name, $new_patch);
        }
}
close IN;

sub create_new_patch($ $ $ $) {
    my($patch_path, $patch_name, $new_patch, $recursive) = @_;
    if ($recursive && ! -d $patch_path) {
        if ($patch_path eq "") {
            print("No patch path ignoring this part, probably comments\n");
            return;
        }
        mkpath([$patch_path], 0, 0777)
          or die "Could not create directory path $patch_path: $!";
    }
    if (!$recursive) {
	$patch_path = "./";
    }
    my $patch_file = $patch_path.$patch_name.".patch";
    open OUT, ">$patch_file"
      or die "Could not create patch $patch_file: $!";
    print OUT $new_patch;
    close OUT;
}

sub get_patch_path_and_name() {
    my($patch_command) = @_;
    my @patch_args = split(" ", $patch_command);
    my $new_file = pop(@patch_args);
    my @new_file_dirs = split($delimiter, $new_file);
    my $patch_name = pop(@new_file_dirs);
    my($patch_path, $junk) = split($patch_name, $new_file);
    return $patch_path, $patch_name;
}
