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

use File::Basename;

print "Copying binary modules from 5.0 to 5.7\n";

$newdir="..";
$map="./cpbin.conf";
for $arg (@ARGV) {
    if ( $arg  =~ /-h|help|-help/ )
    { 
        print "Usage: link [options]\n";
        print "Options\n";	 
        print "-old=DIR   grass 5.3.0 ARCH_DISTDIR (required)\n"; 
        print "-new=DIR   grass 5.7 ARCH_DISTDIR (required)\n";
        print "-conf=FILE  list of modules\n";
        print "           (default is ./cpbin.conf)\n";		 
	exit;
    }
    if ( $arg  =~ s/-old=// ){ $olddir=$arg; }    
    if ( $arg  =~ s/-new=// ){ $newdir=$arg; }
    if ( $arg  =~ s/-conf=// ){ $map=$arg; }
}

#Test if dirs exist
if ( length ($olddir) == 0 ) { die "-old= was not specified\n"; }
if ( length ($newdir) == 0 ) { die "-new= 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 = "$olddir/etc/bin/cmd/$r";
        $new = "$newdir/etc/bin/cmd/$r";
        $newln = "$newdir/bin/$r";

	if ( -f $old ) { 
            if ( -f $new ) {
                print STDERR "'$new' already exists.\n";
                next;
            }
             
            $cmd = "cp $old $new";
            #print "$cmd\n";
            system $cmd;
          
            $cmd = "ln $newdir/etc/front.end $newln";
            #print "$cmd\n";
            system $cmd;
	}
        else
        {
            print STDERR "'$old' doesn't exist\n";
        }
    }	
}
close MAP;  

exit
