#!/usr/pkg/bin/perl
# Original author: Ulrich Pfeifer
# modified jglick@sig.bsh.com:
# $Id: prcs-ediff 1.2 Sat, 11 Apr 1998 17:54:43 -0700 jmacd $

use strict;
use Cwd qw(cwd);

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

my $pwd = cwd;

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

# Make paths absolute (could use &File::PathConvert::rel2abs)
for ($Working_file, $Common_file, $Selected_file, $Output_file) {
  $_ = $pwd . '/' . $_ unless m!^/!;
}

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

if ($use_emerge) {
  # emerge supports a quit-hook as argument
  my $I_am_finished = 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_finished));
  } else {
    $command = 
      qq((emerge-files nil "$Working_file" "$Selected_file" "$Output_file"
          nil $I_am_finished));
  }
} 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.
  # State kept in control buffer for safety.

  $command = <<LISP;
(require \'prcs-ediff)
LISP
  
  if ($Common_file ne '/dev/null') {
    $command .= <<LISP;
(ediff-files-internal
 "$Working_file" "$Selected_file" "$Common_file" 
 nil \'ediff-merge-files-with-ancestor)
LISP
  } else {
    $command .= <<LISP;
(ediff-files-internal
 "$Working_file" "$Selected_file" nil 
 nil \'ediff-merge-files)
LISP
  }

  $command .= <<LISP;
(prcs-merge-startup \'((working-file . "$Working_file")
                       (selected-file . "$Selected_file")
                       (common-file . "$Common_file")
                       (working-label . "$Working_label")
                       (selected-label . "$Selected_label")
                       (common-label . "$Common_label")
                       (output-file . "$Output_file")
                       (process . $$)
                       (signal . SIG$signal)))
\'OK!
LISP
} 

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

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