#!/bin/sh  -- #perl, to stop looping
eval 'exec $GRASS_PERL -S $0 ${1+"$@"}'
    if 0;

use File::Basename;

print "Linking\n";

$newdir="..";
$map="./link.conf";
$copy = 0;
for $arg (@ARGV) {
    if ( $arg  =~ /-h|help|-help/ )
    { 
        print "Usage: link [options]\n";
        print "Options\n";	 
        print "-old=DIR   grass 5.3.0 source directory (required)\n"; 
        print "-new=DIR   grass 5.7 source directory (default is ..)\n";
        print "-conf=FILE  file mapping old directory structure to new\n";
        print "-copy      copy files instead of create symbolic links\n";
        print "           (default is ./link.conf)\n";		 
	exit;
    }
    if ( $arg  =~ s/-old=// ){ $olddir=$arg; }    
    if ( $arg  =~ s/-new=// ){ $newdir=$arg; }
    if ( $arg  =~ s/-conf=// ){ $map=$arg; }
    if ( $arg  =~ /-copy/ ){ $copy=1; }
}

#Test if dirs exist
if ( length ($olddir) == 0 ) { die "-old= was not specified\n"; }
if ( !-d $olddir ) { die "directory: $olddir doesn't exist\n"; }
if ( !-d $newdir ) { die "directory: $newdir doesn't exist\n"; }
if ( !-e $map ) { die "file: $map doesn't exist\n"; }

open (MAP, "<$map") or die "Cannot open $map file\n"; 
while ($r=<MAP>)
{
    chomp $r; 
    $r =~ s/\s+/ /g;
    $r =~ s/^ +//g;
    $r =~ s/#.*//;
    if ( length ($r) > 0 ) 
    {    
        ($old, $new)  = split / +/, $r;
	if ( length ($old) == 0 or length ($new) == 0 ) { next; }
	if ( -d "$olddir/$old" or -f "$olddir/$old" ) 
	{ 
	    # link dirs and files directly
	    lnk ( "$olddir/$old", "$newdir/$new" );
	    next;
	}
	else
	{
	    $oldlist = `ls -d $olddir/$old`;
	    $oldlist =~ s/\s+/ /g;
	    foreach $o ( split / /, $oldlist )
	    {
		# ignore subdirs
		if ( -d "$o" ) { 
		   # message commented, seems to be confusing:
		   # print "Subdir ignored: $o\n";  
		    next; 
		}

		# link files
		$n = $o;
		$n =~ s/.+\///; 
		lnk ( "$o", "$newdir/$new/$n" );
		if ( basename($o) ne "Gmakefile" )
		   { print "Linked $o\n";}
	    }
	}    
    }	
}
close MAP;  

sub lnk {
    $oldpath = @_[0];
    $newpath = @_[1];     
    $oldbase = ~ s/.+\///;
    
    # ignore Gmakefiles 
    if ( $oldpath =~ /Gmakefile/ ||  $oldpath =~ /makefile/ || $oldpath =~ /Makefile/   ) { return; }    

    if ( -e $newpath ) { return; } 
  
    if ( $copy == 1 ) {
        $cmd = "cp -R $oldpath $newpath";
    } else {
        $cmd = "ln -s $oldpath $newpath";
    }
    #print "$cmd\n";
    system $cmd;
    return;
}

exit
