#!/usr/bin/perl -w

use Cwd;
use Getopt::Long;
use File::Basename;


#
# Beginnings of a patch manager. This one is quite similar to
# patch-scripts from Andrew Morton, but
#
# a) contained in one file
# b) uses a different file layout
#
# The file layout:
#
# $projectdir/.patches			directory with patches
# $projectdir/.patches/<name>.patch	one specific patch
# $projectdir/.patches/<name>.files	which files are touched by this patch
# $projectdir/.patches/<name>.txt	optional description
# $projectdir/.patches/series		sequence of available patches
# $projectdir/.patches/applied		sequence of patches that led to current files
#
# More in the perldoc section below
#

use strict;

my $debug = 0;			# debug level
my $do_refresh = 0;		# -r --refresh option
my $do_back = 0;		# -b --back --pop option
my $do_apply = 0;		# -a --apply option
my $do_help = 0;		# -h --help option
my $do_force = 0;		# -f --force option
my $do_import = 0;		# -i --import option
my $do_convpatchscripts = 0;	# --convert-from-patchscripts option
my $do_show = 0;		# -s option
my $do_prefixstrip = 1;		# -p --prefixstrip option
my $interactive = 1;		# disables some NOTE: prints if enabled
my $projectdir = '';		# where we found the .patches directory
my $origdir;			# directory of invocation
my $patchname = '';		# current name of the patch
my @applied;			# list of all currently applied patchs, used to go backwards
my @series;			# list of all usable patches, used to apply next patch
my %applied;			# quick index to find out what is in @applied
my %series;			# quick index to find out what is in @series
my $lastapplied = '';		# the last applied patch
my @patchfilelist;		# list of files that get patched by the current patch
my %patchfilelist;		# quick index to find out what is in @patchfilelist



=head1 NAME

patcher - a patch maintenance tool

=head1 SYNOPSIS

=over 20

=item patcher [-n <patchname>] [<file ...>]

Edit <file> as part of the patch <patchname>

=item patcher -r

Refresh current patch

=item patcher -b

Move back one patch to the previous one.

=item patcher -a

Apply the next patch in the series.

=item patcher -n <patchname> [-p <n>] -i <diff>

Import an external diff file into patch <patchname>. Strip <n> levels from
the directory names. Please note that patch allows '-p1', but we only '-p
1'.

=item patcher [-i <patchname>] [-p <n>] -i <patch ...>

Import an external diff file into patch <patchname>. Strip <n> levels from
the directory names. Please note that patch allows '-p1', but we only '-p
1'.

=back

=head1 INTRO

Patcher is a perl script which I use for managing patches.  It's quite
powerful, easy to use, and fast.

The key philosophical concept is patcher keeps track of which files you
change. It then can generate patches from your changes, no need for you
to handle the diff tool manually.

=head1 DESCRIPTION

Later we will have a walkthrought, but let me first explain the basic
operation modes of patcher:

=head2 Editing files

When you call patcher with a filename, patch will make a backup of this file
(if the file exists).  Now you can create or change the file. Later you can
ask patcher to create a unified diff with all your changes.

=head2 Creating unified diffs

Just call "patcher -r" and you will get a unified diff of all your
additions, modification and deletions. The diff will be stored in
.patches/<patchname>.patch. It is in a form that allows direct application
via patch(1) or, of course, via "patcher -i".

Whenever you do "patcher -r" your .patches/<patchname>.patch file get's
refreshed.

=head2 Revoking a patch

To revoke your changes and go to the previous version, just enter
"patcher -b". Patcher will make sure that you don't loose your changes
by asking you to create a diff if something has changed since the last
refresh. You can --force patcher to go back anyway.

=head2 Re-applying a patch

With "patcher -n <patchname> -a" one can apply an already existing
managed patch. Patcher tests if the patch would apply without problem and
applies it.

=head2 Importing existing patches

Sometimes you have an external patch. When you import this patch with
"patcher -i" then patcher will remember which files have changed. Now
you can edit some files and refresh the patch, getting a newer or a
refined version of the patch.

=head1 INSTALLATION

You place patcher somewhere in your path.

Patcher requires one  special directory called ".patches". It will search
for this directory. If it does not exist, patcher creates it automatically.

You can have lot's of these directories, one for each project you work an.
They don't interfere.

=head1 CONCEPTS

All work occurs with a single directory tree. All commands are invoked
within the root of that tree (TODO: this can and should change). Patcher manages a
"stack" of patches.

Each patch is a changeset against the base tree plus the preceding patches.

All patches are listed, in order, in the file ".patches/series". You manage the
series file.

Any currently-applied patches are described in the file
".patches/applied". The patcher manage this file.

Each patch affects a number of files in the tree. These files are
listed in a file list named ".patches/*.files". Patcher manages them.

Patches are placed into ".patches/*.patch" files.

Optionally you can put descriptions for the patches in files named
".patches/*.txt".

So for a particular patch "my-first-patch" the following will exist:

=over

=item -

An entry "my-first-patch.patch" in ".patches/series".

=item -

An entry "my-first-patch" in ".patches/applied" (if it's currently applied)

=item -

A file ".patches/my-first-patch.files" which contains the names of the
files which my-first-patch modifies, adds or removes

=item -

A file ".patches/my-first-patch.patch", which is the context diff, basically the
main output of patcher.

=item -

Optionally a file ".patches/my-first-patch.txt" which contains the patch's
changelog, description or whatever you put in there.

=back

=head1 WALKTHROUGHT

Let's start.

Go into /usr/src/linux (or wherever)

Now let's generate a patch

	patcher -n my-patch kernel/sched.c

OK, we've copied kernel/sched.c to kernel/sched.c~my-patch. We've
appended "my-patch" to ".patches/applied" and we've put "kernel/sched.c"
into the patch file list, ".patchesmy-patch.files".

	Now edit kernel/sched.c a bit.

Now we're ready to document the patch

	Now write .patches/my-patch.txt

Now generate the patch

	patcher -r

This will generate ".patches/my-patch.patch". Take a look.

Now remove the patch by going backwards:

	patcher -b

applied is now empty, and the patch is removed.

Now let's add a file to my-patch. First we re-apply the patch. my-patch has
been put into the ".patches/series" file, so we can simply apply the next patch:

	patcher -a

OK, the patch is applied again. Let's add another file

	patcher kernel/printk.c

Note that here we gave patcher a single argument. So rather than
opening a new patch, it adds kernel/printk.c to the existing topmost
patch. That's my-patch.

	Edit kernel/printk.c

Refresh my-patch (you end up running refpatch a lot)

	patcher -r

Now start a second patch:

	patcher -n my-second-patch kernel/sched.c

Now take a look at ".patches/applied". Also do an `ls kernel/sched*'.

	Edit kernel/sched.c, to make some changes for my-second-patch

Generate my-second-patch:

	patcher -r

Take a look in ".patches/my-second-patch.patch".

Also note that "my-second-patch.patch" has been added to the series file. Whenever
you manually begin a patch, it will automatically be put into the series file.

In this way, the whole thing is stackable. If you have four patches
applied, say "patch-1", "patch-2", "patch-3" and "patch-4", and if
patch-2 and patch-4 both touch kernel/sched.c then you will have:

=over 30

=item kernel/sched.c~patch-2

Original copy, before patch-2

=item kernel/sched.c~patch-4

Copy before patch-4. Contains changes from patch-2

=item kernel/sched.c

Current working copy. Contains changes from patch-4.

=back

This means that your diff headers contain "~patch-name" in them, which
is convenient documentation.

To end our tour, we remove both patches:

	patcher -b
	patcher -b

That's pretty much it, really.

=head1 SEE ALSO

Andrew Morton's patch scripts at http://www.zip.com.au/~akpm/linux/patches/

I stole the idea from him and even most of this documentation.

=head1 AUTHOR

Holger Schurig <holgerschurig usingthedomain gmx.de>

=cut




#
# Find and/or create a Patch directory
#
# a) look in current directory for .patches directory
# b) if not found, descent and look again
# c) if at /, create a .patches directory at the original place
#
sub FindProcjectDirectory()
{
	print "DEBUG: FindProjectDirectory()\n" if $debug > 1;

	return if $projectdir;

	$origdir = "";
	while (1) {
		$projectdir = cwd();
		$origdir ||= $projectdir;
		last if $projectdir eq '/';
		if (-d '.patches') {
			print "DEBUG: found .patches/ in $projectdir/\n" if $debug > 1;
			chdir $origdir;
			return;
		}
		chdir '..';
	}
	$projectdir = $origdir;
	print "NOTE: made $projectdir to projectdir by creating .patches/\n";
	chdir $projectdir;
	mkdir '.patches' or die "$!\n";
}



#
# This loads the contents of the file .patches/series into @series and %series
#                            and from .patches/applied into @applied and %applied
# After this, $lastapplied is the name of the last applied patch
#
sub LoadSeriesAndApplied()
{
	print "DEBUG: LoadSeriesAndApplied()\n" if $debug > 1;

	@applied = ();
	%applied = ();
	@series  = ();
	%series  = ();

	if (open APPLIED, "$projectdir/.patches/applied") {
		while (defined($_ = <APPLIED>)) {
			chomp;
			next if /^\s*$/;
			next if /^#/;
			next if $applied{$_};
			push @applied, $_;
			$applied{$_} = 1;
			$lastapplied = $_;
		}
		close APPLIED;
	}

	if (open SERIES, "$projectdir/.patches/series") {
		while (defined($_ = <SERIES>)) {
			chomp;
			next if /^\s*$/;
			next if /^#/;
			next if $series{$_};
			push @series, $_;
			$series{$_} = 1;
		}
		close SERIES;
	}

	if ($debug > 2) {
		print "DEBUG: applied: ", join(" ", @applied), "\n" if @applied;
		print "DEBUG: series:  ", join(" ", @series),  "\n" if @applied;;
	}
}



#
# This saves the contents of @series and @applied into .patches/{series,applied}
#
sub SaveSeriesAndApplied()
{
	print "DEBUG: SaveSeriesAndApplied()\n" if $debug > 1;

	open SERIES, ">$projectdir/.patches/series" or die "$!\n";
	print SERIES join("\n", @series, '');
	close SERIES;

	open APPLIED, ">$projectdir/.patches/applied" or die "$!\n";
	print APPLIED join("\n", @applied, '');
	close APPLIED;
}




#
# Whenever we patch a file, we first make a backup copy of the unchanged file in
# it's current directory. This will later be used to re-create a patch.
#
sub GetBackupName($)
{
	my $fname = shift;
	print "DEBUG: GetBackupName('$fname')\n" if $debug > 2;

	return "$fname~$patchname";
}



#
# For every applied patch we have a list of the files modified by the patch
# in .patches/<$patchname>.files. We load this in to @patchfilelist.
#
sub LoadPatchFilelist($)
{
	my $pname = shift;
	print "DEBUG: LoadPatchFilelist('$pname')\n" if $debug > 1;

	@patchfilelist = ();
	%patchfilelist = ();
	if (open FILES, "$projectdir/.patches/$pname.files") {
		while (defined($_ = <FILES>)) {
			chomp;
			next if /^\s*$/;
			next if /^#/;
			print "DEBUG: putting '$_' into \@patchfilelist\n" if $debug > 1;
			push @patchfilelist, $_;
			$patchfilelist{$_} = 1;
		}
		close FILES;
	}
}



#
# Puts a file into a patch
#
# a) check for name of patch to put it into
# b) check if the file is already in the patch
# c) create backup copy
# d) add it to the list of files
# e) add it to @applied and @series, if necessary
#
sub PutIntoPatch($)
{
	my $fname = shift;
	print "DEBUG: PutIntoPatch('$fname')\n" if $debug > 1;

	if (!$patchname && $lastapplied) {
		$patchname = $lastapplied;
		#print "NOTE: --name was missing, using '$patchname' as patch name\n";
	}
	unless ($patchname) {
		print "ERROR: you want to patch a file, but I can't find into which patch this file\n";
		print "       file belongs. Please use the --name parameter.\n";
		exit(1);
	}

	my $backupname = GetBackupName($fname);
	if (-f $backupname) {
		print "WARNING: file seems to be already in patch\n";
	}
	elsif (-f $fname) {
		print "DEBUG: creating backup copy $backupname\n" if $debug;
		system('/bin/cp', '-a', $fname, $backupname);
	} else {
		print "DEBUG: file $fname does not exist\n" if $debug > 1;
	}
	
	print "DEBUG: adding $fname to $patchname.files\n" if $debug;
	open FILES, ">>$projectdir/.patches/$patchname.files" or die "$!\n";
	print FILES "$fname\n";
	close FILES;

	my $added = 0;
	unless ($applied{$patchname}) {
		print "DEBUG: adding '$patchname' to applied\n" if $debug;
		push @applied, $patchname;
		$applied{$patchname} = 1;
		$added = 1;
	}
	unless ($series{$patchname}) {
		push @series, $patchname;
		$series{$patchname} = 1;
		print "DEBUG: adding '$patchname' to series\n" if $debug;
		$added = 1;
	}
	if ($added) {
		SaveSeriesAndApplied();
	}
}



#
# General patch applier
#
# a) only apply not-yet-applied patches, based on @applied
# b) only apply not-yet-applied patches, based on patch -R
# c) only apply patches that apply cleanly
# d) call PutIntoPatch for all touched files so that the backups and @patchfilelist are ok
# e) finally apply patch
#
sub ApplyPatchWith($)
{
	my ($opt) = @_;

	my $patchlog = "$projectdir/.patches/.tmp.$$";

	# First we check if the patch with this name is already in our database
	if ($applied{$patchname}) {
		print "NOTE: patch with name '$patchname' already applied\n";
		return 1;
	}

	# Then we also look if the files are already patched
	print     "DEBUG: patch --dry-run -R $opt\n" if $debug > 1;
	my $res = system("patch --dry-run -R $opt >$patchlog");
	if ($res == 0) {
		print "NOTE: the modifications in patch '$patchname' are no longer necessary\n";
		unlink($patchlog);
		return 1;
	}

	# When we look if the patch would apply cleanly
	print  "DEBUG: patch --dry-run $opt\n" if $debug > 1;
	$res = system("patch --dry-run $opt >$patchlog");
	if ($res != 0) {
		print "ERROR: this patch does not apply cleanly\n";
		unlink($patchlog);
		return 1;
	}

	# and if this worked,
	# - we apply the patch
	# - we scan the output of the application to find out which files have
	#   been modified and put them into our database, this also creates
	#   backup copies
	unlink("$projectdir/.patches/$patchname.files");
	if (open PATCHLOG, $patchlog) {
		while (defined($_ = <PATCHLOG>)) {
			chomp;
			next unless /^patching file (.+)$/;
			PutIntoPatch($1);
		}
		close PATCHLOG;
	}

	# Finally we apply the patch. No need to create backup copies with -b,
	# that has been done by PutIntoPatch()
	print  "DEBUG: patch $opt\n" if $debug > 1;
	$res = system("patch $opt >$patchlog");
	unlink($patchlog);
	if ($res != 0) {
		print "ERROR: strange, with --dry-run the patch worked, but without it does not work ...\n";
		return 1;
	}

	# TODO: put header of patch into .patches/<$patchname>.txt

	return $res;
}



#
# This simply applies the next patch, based on info in @series and @applied
#
sub ApplyNextPatch()
{
	print "DEBUG: ApplyNextPatch()\n" if $debug > 1;

	unless (@series) {
		print "ERROR: no entries in ./patches/series\n";
		exit(1);
	}

	if ($#applied == $#series) {
		print "ERROR: all patches already applied\n";
		exit(1);
	}

	$patchname = $series[$#applied+1];
	print "NOTE: applying '$patchname'\n"; 

	# -E	remove empty files
	# -p1	delete 1 prefix dir
	my $opt = "-E -p1 <$projectdir/.patches/$patchname.patch";
	my $res = ApplyPatchWith($opt);
	if ($res == 0) {
		print "NOTE: patch '$patchname' applied\n" if $debug;
		$lastapplied = $patchname;
	} else {
		print "ERROR: patch '$patchname' did not apply\n";
		exit(1);
	}
}



#
# We want to edit a file. So we have to:
# a) normalize filename: convert to full path, then strip projectdir in front away
# b) look if the file has already been put into a patch
#    if yes: edit the file
#    if no: complain
#
sub EditFile($)
{
	my $fname = shift;
	print "DEBUG: EditFile('$fname')\n" if $debug > 1;

	if ($patchname) {
		if (($patchname ne $lastapplied) && -f "$projectdir/.patches/$patchname.files") {
			print "ERROR: we can only edit files in the current or in a new patch.\n";
			print "       Try -p to pop back to '$patchname'.\n";
			exit(1);
		}
	} else {
		if ($lastapplied) {
			$patchname = $lastapplied;
			print "NOTE: assuming '$patchname' as patch name\n" if $debug;
		} else {
			print "ERROR: you want to patch a file, but I can't find into which patch this file\n";
			print "       file belongs. Please use the --name parameter.\n";
			exit(1);
		}
	}

	LoadPatchFilelist($patchname);
	unless ($patchfilelist{$fname}) {
		PutIntoPatch($fname);
	}

	if ($ENV{EDITOR}) {
		print "NOTE: editing file $fname\n";
		system($ENV{EDITOR}, $fname);
	} else {
		print "now edit file $fname\n";
	}
}


#
# This get's the list of changed-files per patch and diffs the backup copies
# against the current situation. The diffs will be put into the $patchname.patch file
#
sub RefreshPatch()
{
	print "DEBUG: RefreshPatchSet()\n" if $debug > 1;

	if (!$patchname && $lastapplied) {
		$patchname = $lastapplied;
		#print "NOTE: --name was missing, using '$patchname' as patch name\n" if $debug;
	}
	unless ($patchname) {
		print "Can't refresh unnamed patch: please specify name of a patch with --name first\n";
		exit(1);
	}

	my $patch = "$projectdir/.patches/$patchname.patch";
	my $desc  = "$projectdir/.patches/$patchname.txt";

	unlink $patch;
	if (-f $desc) {
		system('/bin/cp', $desc, $patch);
		system("/bin/echo >$patch");		# ensure we have a trailing CRLF
	} else {
		print "WARNING: Description for patch '$patchname' missing\n" if $debug > 3;
	}

	open FILES, "$projectdir/.patches/$patchname.files";
	my $dir = basename($origdir);
	chdir('..');
	my $fname;
	while (defined($fname = <FILES>)) {
		chomp($fname);
		my $backupname = GetBackupName($fname);
		if (-f "$dir/$backupname") {
			$backupname = "$dir/$backupname";
		} else {
			$backupname = '/dev/null';
		}
		# -u	unified diff
		# -d	find perhaps smaller set of changes
		my $opt = "-ud $backupname $dir/$fname";
		print "DEBUG: diff $opt\n" if $debug;
		system("diff $opt >>$patch");
		
	}
	close FILES;
	chdir($origdir);

	print "NOTE: patch '$patchname' refreshed\n" if $interactive;
}



#
# The oppiste of ApplyNextPatch()
#
sub BackOnePatch()
{
	print "DEBUG: BackOnePatch()\n" if $debug > 1;

	unless ($lastapplied) {
		print "ERROR: no patch currently applied\n";
		exit(1);
	}
	$patchname = $lastapplied;

	my $patchfile = "$projectdir/.patches/$patchname.patch";
	unless (-f $patchfile) {
		print "ERROR: patch file for '$patchname' does not exist\n";
		exit(1);
	}

	# Check if current patch is up-to-date, using these options:
	# -R	reverse
	# -E	remove empty files
	# -f	force
	# -s	silent
	# -p1	all of our self-generated patches are -p1 patches
	my $res = system("patch --dry-run -R -f -s -p1 <$patchfile >/dev/null");
	if ($res == 0) {
		print "NOTE: patch '$patchname' taken back\n";
	} else {
		if ($do_force) {
			print "WARNING: loosing patch information because of -f flag\n";
		} else {
			print "ERROR: patch '$patchname' has not been refreshed.\n";
			print "       either refresh with -r or force operation with -f\n";
			exit(1);
		}
	}


	# I have two options: I just revert the patch via patch -R ... 
	#                     or I could go thought .patches/$patchname.files
	# I think I'll go the second way
	
	if (open FILES, "$projectdir/.patches/$patchname.files") {
		while (defined($_ = <FILES>)) {
			chomp;
			print "DEBUG: going to previous '$_'\n" if $debug;
			my $backupname = GetBackupName($_);
			if (-f $backupname) {
				rename $backupname, $_;
			} else {
				unlink $_;
			}
		}
		close FILES;
	}

	# we re-create the list of files on-the-fly when doing "patcher -a"
	unlink("$projectdir/.patches/$patchname.files");

	pop @applied;
	delete $applied{$patchname};
	$lastapplied = $applied[-1];
	if (@applied) {
		print "NOTE: now at '$lastapplied'\n" if $interactive;
	} else {
		print "DEBUG: that was the last patch\n" if $debug;
	}
	SaveSeriesAndApplied();
}



sub BackPatch(@)
{
	unless (@ARGV) {
		BackOnePatch();
		return;
	}

	if ($#ARGV > 0) {
		print "ERROR: only one argument to -b allowed\n";
		exit(1);
	}

	my $target = $ARGV[0];

	# TODO: numerical argument

	unless ($applied{$target}) {
		print "ERROR: no patch named '$target' currently applied\n";
		exit(1);
	}

	$interactive = 0;
	while ($lastapplied ne $target) {
		BackOnePatch();
	}
	print "NOTE: now at '$lastapplied'\n";
}


#
# Apply ...
# - the next patch if called without arguments
# - all patches up-to-and-including the specified patch
# - a not-yet-in-the-series patch at the current position
#
sub ApplyPatch(@)
{
	my (@what) = @_;
	print "DEBUG: ApplyNextPatch(...)\n" if $debug > 1;

	unless (@what) {
		ApplyNextPatch();
		return;
	}

	my $target;
	foreach $target (@what) {
		print "DEBUG: looking for patch '$target'\n" if $debug;

		# TODO: numerical arguments to forward n patches

		# The patch is already applied
		if ($applied{$target}) {
			print "NOTE: patch '$target' already applied\n";
			next;
		}

		# The patch is not yet applied, but in series
		if ($series{$target}) {
			print "DEBUG: patch '$target' is in series, going forward\n" if $debug;
			while ($lastapplied ne $target) {
				ApplyNextPatch();
				next if $lastapplied eq 'pxa';
			}
			next;
		}

		# The patch is not yet applied and not in series
		if (-f "$projectdir/.patches/$target.patch") {
			print "NOTE: '$target' will be inserted at the current position into .patches/series\n";
			# insert new patch at current position
			splice @series, $#applied+1, 0, $target;
			$series{$target} = 1;
			ApplyNextPatch();
			next;
		}

		print "ERROR: patch '$target' unknown, maybe you need to import (-i) it?\n";
		exit(1);
	}
}



#
# Import an external patch and make it known to patcher
#
sub ImportExternalPatch($)
{
	my $fname = shift;
	print "DEBUG: ImportExternalPatch('$fname')\n" if $debug > 1;

	# TODO: if no --name option has been given we could try to find a patchname
	# based on the filename. Here is some code, which I have to test. The
	# print DEBUG will vanish once I'm satisfied.
	my $suggest = $fname;
	$suggest =~  s/.gz$//;			# strip .gz
	$suggest =~  s/.bz2$//;			# strip .bz2
	$suggest =~  s/.diff$//;		# strip .diff
	$suggest =~  s/.patch$//;		# strip .patch
	$suggest =~  s/^diff[-.]?//;		# strip .diff
	$suggest =~  s/^patch[-.]?//;		# strip .patch
	$suggest =~  s/(.*)_[0-9\.\-]*/$1/;	# util-linux_1234 -> util-linux
	$suggest =~  s/.*\/([^\/]+)/$1/;	# remove preceeding directories
	if ($patchname) {
		print "DEBUG: $suggest $patchname\n" if $suggest ne $patchname;
	} else {
		$patchname = $suggest;
	}

	# check if the patch would apply
	# -f	force
	# -E	remove empty output files
	# -p	prefix strip
	my $opt = "-f -E -p$do_prefixstrip <$fname";

	print "NOTE: import patch '$fname' as '$patchname'\n";
	ApplyPatchWith($opt);

	# Refresh the patch so that we have some usable .patches/*.patch file
	$interactive = 0;
	RefreshPatch();
}



#
# For people that used Andrew Morton's patch scripts and want to convert
#
sub ConvertFromPatchScripts()
{
	print "ConvertFromPatchScripts()\n" if $debug > 1;

	chdir($projectdir);
	unless (-d 'patches' && -d 'pc' && -d 'txt') {
		print "ERROR: $projectdir has not been maintained with Andrew Morton's patch-scripts\n";
		exit(1);
	}
	my $fn;

	chdir("$projectdir/patches");
	foreach $fn (glob '*.patch') {
		print  "cp -a $fn $projectdir/.patches/$fn\n" if $debug;
		system("cp -a $fn $projectdir/.patches/$fn");
	}

	chdir("$projectdir/pc");
	foreach $fn (glob '*.pc') {
		$_ = $fn;
		s/\.pc$/.files/;
		print  "cp -a $fn $projectdir/.patches/$_\n" if $debug;
		system("cp -a $fn $projectdir/.patches/$_");
	}

	chdir("$projectdir/txt");
	foreach $fn (glob '*.txt') {
		print  "cp -a $fn $projectdir/.patches/$fn\n" if $debug;
		system("cp -a $fn $projectdir/.patches/$fn");
	}

	chdir($projectdir);
	print  "cp -a applied-patches .patches/applied\n" if $debug;
	system("cp -a applied-patches .patches/applied");
	print  "cp -a series .patches\n" if $debug;
	system("cp -a series .patches");	


	exit(0);
}



#
# Show status of patches in .patches, @series and @applied
#
sub ShowStatus()
{
	print "ShowStatus()\n" if $debug > 1;


	# Find any patches that are not in the series files and display
	# them as orphaned:

	chdir("$projectdir/.patches");
	foreach (glob "*.patch") {
		s/\.patch$//;
		next if $series{$_};
		my $stat = 'not in series';
		$stat = 'orphan applied' if $applied{$_};
		printf "%-14s %-13s %s\n", $stat, -f "$projectdir/.patches/$_.txt" ? '' : '.txt missing', $_;
	}


	# Display status of all patches in the series file:

	foreach (@series) {
		my $stat = 'series';
		$stat = 'series applied' if $applied{$_};
		printf "%-14s %-13s %s\n", $stat, -f "$projectdir/.patches/$_.txt" ? '' : '.txt missing', $_;
	}


}


sub usage
{
	print <<EOF;
Usage:
    patcher [-name <name>] file      edit file
    patcher -r                       re-create .patches/<name>.patch
    patcher -a                       apply next patch of .patches/series
    patcher -a <patch>               apply all patch and all predecessors
    patcher -b                       back out last patch
    patcher -b <patch>               back patches until we're at <patch>
    patcher [-p <num>] -i file       import external patch
    patcher -s                       show state of patch system
EOF
    exit(shift);
}


$_ = GetOptions(
	'debug+' => \$debug,
	'help' => \$do_help,
	'refresh' => \$do_refresh,
	'back' => \$do_back,
	'apply' => \$do_apply,
	'import' => \$do_import,
	'show' => \$do_show,
	'convert-from-patchscripts' => \$do_convpatchscripts,
	'force' => \$do_force,
	'p|prefixstrip=i' => \$do_prefixstrip,
	'name=s' => \$patchname
	) || usage(2);
usage(1) if $do_help;

FindProcjectDirectory();

if ($do_convpatchscripts) {
	ConvertFromPatchScripts();
}

LoadSeriesAndApplied();

if ($do_refresh) {
	RefreshPatch();
}

if ($do_back) {
	BackPatch(@ARGV)
}
elsif ($do_apply) {
	ApplyPatch(@ARGV);
}

if ($do_show) {
	ShowStatus();
}

exit(0) if $do_refresh
	|| $do_back
	|| $do_apply
	|| $do_show;


usage(1, "$0: no files given\n") unless @ARGV;

foreach (@ARGV) {
	if ($do_import) {
		ImportExternalPatch($_)
	} else {
		EditFile($_);
	}
}

SaveSeriesAndApplied();
0;

