# Copyright (c) 1993, 1994, 1995, 1996, 1997, 1998, 1999 by RIPE NCC
#
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of the author not be
# used in advertising or publicity pertaining to distribution of the
# software without specific, written prior permission.
#
# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL
# AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
# AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# 
# uninstall <installed> <built>
#
# remove file <installed> if it 'cmp's with <built>
#
# $Id: remove.pl,v 1.4 1999/10/06 16:40:39 marek Exp $

use strict;

{
  # check both files exist

  {
    my $file;
    foreach $file (@ARGV) {
      unless (-e $file ) {
	print "$file missing\n";
	exit 0;
      }
    }
  }

  my %installed;
  my %built;

  $0 =~ s:.*/::;
  die "usage: $0 <file1> <file2>\n" unless (@ARGV == 2);

  $installed{Name} = shift;
  $built{Name} = shift;

  ## get file stats for both files

  @{$installed{Stat}} = stat $installed{Name}
    or die "$installed{Name}: can't stat: $!\n";

  @{$built{Stat}} = stat $built{Name}
    or die "$built{Name}: can't stat: $!\n";

  ## compare files 
  ## first check file size - if same check contents

  if ($installed{Stat}->[7] != $built{Stat}->[7] ||
      differp ($installed{Name}, $built{Name})) {

    print "$installed{Name} has CHANGED!\n";
    exit 0;
  }
  
  # unlink installed file

  unlink $installed{Name} or
    die "can't unlink $installed{Name}: $!\n";

  print "$installed{Name} removed\n";

  exit 0;
}

# read through two files to see if they differ
# return undef if they are the same

sub differp {
  my ($namea, $nameb) = @_;

  open A, $namea
    or die "can't open [$namea]: $!\n";

  open B, $nameb
    or die "can't open [$nameb]: $!\n";

  my ($a, $b);
  while (defined ($a=<A>) and defined ($b=<B>)) {
    ($a eq $b) or
      return 1;
  }

  return undef;
}    
