#!/usr/bin/perl -w
# $Id: fixsymlinks.pl,v 1.2 1998/07/29 12:37:33 ray Exp ray $
#use strict;

my $C = $0; $C =~ s%.*/%%;


my $Help = 0;
my $verbose = 0;
my $manGz = "";
my $debug = 0;

sub Usage ($$) {
  my( $rv, $msg) = @_;
  print( STDERR $msg . "\n") if ( $msg );
  printf( STDERR "Usage: $C [options] dir ...\n");
  $rv = 0 if ( $Opt{'help'} );
  exit( $rv);
}

{
  use Getopt::Long;
  $Getopt::Long::debug = 0;
  $Getopt::Long::ignorecase = 0;
  #$Getopt::Long::pass_through = 1;
  $Getopt::Long::bundling = 1;
  %Opt = ();

  Usage(1, "") unless ( GetOptions( \%Opt,
        'help|h', 'verbose|v', 'debug|d',
	'man-gz|m=s') && ! $Opt{'help'} );

  $verbose ++ if ( $Opt{'verbose'} );
  ( $debug ++, $verbose ++ ) if ( $Opt{'debug'} );

  Usage( 1, "$C: no target(s) specified.") unless ( $#ARGV >= $[ );

  if ( $Opt{'man-gz'} ) {
    $manGz = $Opt{'man-gz'};
    Usage( 2, "$C: $manGz: no such directory.\n") if ( ! -d $manGz );
    $manGz =~ s,([*?+.]),\\$1,g;
  }
}

my $d;
while ( defined( $d = shift) ) {

  ( -d $d ) || die( "$C: $d: no such directory.\n");
  open( SYMLINKS, "find $d -type l -print |" ) ||
     die( "$C: open(SYMLINKS): $!\n");

  my $p;
  my $f;
  my $of;

  if ( $manGz ) {
    $d = $manGz;
  } else {
    $d =~ s,([*?+.]),\\$1,g;
  }

  while ( <SYMLINKS> ) {
    chop( $_);
    $p = $_;
    $f = $of = readlink($p)	|| die( "$C: readlink($p): $!\n");
    # remove trailing component (aka filename)
    $p =~ s,/[^/]*$,,;
    $p =~ s,([*?+.]),\\$1,g;
    # strip all directories from $f, if $_ will be in the same dir as $f
    $f =~ s,^$p/,,;
    # strip "DESTDIR" part from $f, making it absolute...
    $f =~ s,^$d,,;
    if ( $manGz ) {
      if ( -l $_ ) {
	printf( "rm %s\n", $_) if ( $verbose );
	(unlink( $_) == 1)	|| die( "$C: unlink($_): $!\n");
      }
      $_ .= ".gz";
      $f .= ".gz";
    }
    next if ( $f eq $of );
    if ( -l $_ ) {
      printf( "rm %s\n", $_) if ( $verbose );
      (unlink( $_) == 1)	|| die( "$C: unlink($_): $!\n");
    }
    printf( "ln -s %s %s\n", $f, $_) if ( $verbose );
    symlink( $f, $_)	|| die( "$C: symlink( $f, $_): $!\n");
  }

  close( SYMLINKS);
}

exit( 0);
