#!/usr/bin/perl
#                              -*- Mode: Perl -*- 
# $Basename: prcs-ediff $
# $Revision: 1.1 $
# Author          : Ulrich Pfeifer
# Created On      : Fri May  2 08:28:20 1997
# Last Modified By: Ulrich Pfeifer
# Last Modified On: Fri Jul 11 20:47:19 1997
# Language        : CPerl
# Update Count    : 67
# Status          : Unknown, Use with caution!
# 

use strict;
use Cwd;
use File::Copy;

my $use_emerge; # set this to 1 if you don't have the ediff package
                # for emacs installed.


my $pwd = getcwd;

# Get the srguments
my (
    $Working_label,
    $Working_file,
    $Common_label,
    $Common_file,
    $Selected_label,
    $Selected_file,
    $Output_file,
   ) = @ARGV;

# Make pathes absolute
for ($Working_file, $Common_file, $Selected_file, $Output_file) {
  $_ = $pwd . '/' . $_ unless /^\//;
}

my $signal       = 'USR1';
my $command;

if ($use_emerge) {
  # emerge supports a quit-hook as argument
  my $I_am_finshed = qq[(lambda () (signal-process $$ \'SIG$signal))]; 
  if ($Common_file ne '/dev/null') {
    $command = 
      qq[(emerge-files-with-ancestor nil
          "$Working_file" "$Selected_file" "$Common_file" "$Output_file"
          nil $I_am_finshed)];
  } else {
    $command = 
      qq[(emerge-files nil "$Working_file" "$Selected_file" "$Output_file"
          nil $I_am_finshed)];
  }
} else {
  # Ediff uses a global quit-hook. Since it does not support an output
  # file as argument we use the quit-hook to store the file.
  my $I_am_finshed =
    qq[
       (require \'ediff)
       (defun prcs-quit-hook ()
        (mapcar 
         (lambda (f)
          (if (get-buffer f)
           (kill-buffer (get-buffer f))))
         (list "prcs_temp.0" "prcs_temp.1" "prcs_temp.2"))
        (write-file "$Output_file")
        (signal-process $$ \'SIG$signal))

       (add-hook 'ediff-quit-hook 'prcs-quit-hook t)
      ];
  
  if ($Common_file ne '/dev/null') {
    $command = 
      qq[$I_am_finshed
         (ediff-files-internal
          "$Working_file" "$Selected_file" "$Common_file" 
          nil \'ediff-merge-files-with-ancestor)];
  } else {
    $command = 
      qq[I_am_finshed
         (ediff-files-internal
          "$Working_file" "$Selected_file" nil 
          nil \'ediff-merge-files)];
  }
} 

# set up the signal handlers
$SIG{$signal} = sub {
  print "Emerge $$ done\n";
  exit 0;
};

$SIG{CHLD} = sub {
  my $waitedpid = wait;
  my $code      = ($? >> 8);
  
  if ($?) {
    die "Merge failed";
    # We should restore the working file here ;-)
  }
};
  
my $pid;
  
if (!defined($pid = fork)) {
  die  "cannot fork: $!\n";
} elsif ($pid) {
  warn "Started $pid, Try 'kill -$signal $$' to terminate if things mess up\n";
  while (1) {
    #warn "waiting for $$...\n";
    sleep(5);
  }
} else {
  #print STDERR "gnudoit '$command'\n";
  exec 'gnudoit', $command or die "Could not run gnudoit: $!\n";
}

