#!/usr/bin/perl -w 

# This is a perl rewrite of the flatten subsection of
# the slink_cd script.  

#flatten: expects a list of files as standard
#     input.  leaves symlinks into the current tree alone, 
#     changes other links. Needs the directories of the mirror 
#     and the non-us mirror.

# syntax: "cat <files > | flatten mirror non-us debug_level"

# (c) 1998 Jens Ritter
# Apply the GNU Public License V 2 or later if necessary.
#
# Released with slink_cd v 1.13 31 Mar 1999

# We extensively work on $_!

while (<STDIN>)
{
	print "$3\n" if $3;

    chop;          # Chop "\n" from end.
    if ( ! -l )    # If not symlink, next.
    { 
		print $_, ": normal file\n" if $3;
        next; 
    }  

    /^(.*)\/(.*)$/;    # regexps are greedy (replaces basename and dirname).

    $dirname  = $1;

    # Count the number of slashes in $dirname and in the
    # sym-link. If the sym-link has more then we need to
    # remove the (external) sym-link and make a hard link
    
    $dirslash = $dirname =~ s/\//\//g ; # counts the number of slashes
                                       # (by replacing "/" with "/")

    $linkname = readlink;

    $linkslash = $linkname =~ s/\//\//g ; 

    $linkname =~ s/\.\.\///g;
    $abslink = $ARGV[0] . "/dists/" . $linkname;

    # Gross hack for non-US. Sort out the tree!!!
    if ( /non-US/ ) 
    {
		$linkslash = $linkslash + 3;
		$abslink = $ARGV[1] . "/" . $linkname;
    }
 
    # And now for the top-level docs packages; why are these sym-links?
    if ( /package-developer/ ) 
    {
		$abslink = $ARGV[0] . "/" . $linkname;
    }

    if ($dirslash < $linkslash)
    {
		print $_, " out of tree; replacing\n" if $3;
		# Debugging output.
		print "remove: $_\n" if $3;
		print "link: $abslink, $_\n" if $3;

		# Uncomment next to lines to remove safeguard.
		unlink;
		link $abslink, $_;
    }
    else
    {
		print $_, " inside of tree; leaving alone\n" if $3;
	}
    # print $_,",", $i,",", $abslink,".\n";
}