#!/bin/perl
#
# This is a small perl script that emulates gcc with the
# SAS/C compiler. It is mainly created to compile UAE
# with SAS/C to test 68060 optimisations. This scripts also
# manages so that links are properly handled by SAS/C.
#
# (c) 1997 by Samuel Devulder.
#

# dir used so that links are properly handled by SAS/C
$LNDIR = "scc-idir";

# replace all filenames that actually are links
for($i=0;$i<=$#ARGV;++$i) {
    $_ = $ARGV[$i];
    $_=readlink($_) if -l $_;
    if(/\/[^\/]+$/ && -l $`) {
        $_=readlink($`).$&;
	s/.*\/src\///;
	s/^\/([^\/]+)\//$1:/;
    }
    $ARGV[$i] = $_;
}

# create link-dir so that SAS/C can handle header files stored
# in linked directories.
if(! -d $LNDIR) {
     mkdir($LNDIR,0777);
     while(<*>) {
         next if ! -l $_;
         $linkname = $_;
         $realname = readlink($_);
	 $realname =~ s/^\/([^\/]+)\//$1:/; $realname =~ s/[.][.]//g;
         if(-d $linkname) {
             mkdir("$LNDIR/$linkname",0777);
             while(<$linkname/*.h>) {
                open(OUT,">$LNDIR/$_");
                s/^.*\///;
                print OUT "#include \"$realname/$_\"\n";
                close OUT;
             }
         } else {
            open(OUT,">$LNDIR/$linkname");
            print OUT "#include \"$realname\"\n";
            close OUT;
         }
     }
}

# build general command-line
$_ = " @ARGV";

# if preprocess, then use gnu/cpp since pponly in SAS/C
# does not signal missing .h files.
if(/\s+-E/) {
         exit system("cpp -DAMIGA -nostdinc -I\/include -D__SASC$_");
}

# fast but not perfect unix-to-amiga path translation 
s/[.][.]//g;
s/[.][\/]//g;

# if no destination, then assume a.out
$_ .= " -o a.out" if !/\s-[cEo]/;

# command-line modification
s/\s+-I\s*/ IDIR=/g;                # process include dirs
s/\s+-o/ OBJNAME/g;                 # process output file
s/\s+-g/ DBG FF/g;                  # process debug 
s/\s+-lm/ MATH=STD/g;               # math library
s/\s+-l\s*(\w+)/ LIB=LIB:$1.lib/g;  # other librarys
s/\s+-D\s*/ DEF=/g;                 # preprocessor defines
s/\s+-traditional-cpp//g;           # 
s/\s+-m(\w+)/ CPU=$1/g;          # specific cpu code generation
s/\s+-O(\d?)/ OPT OPTSCHED OPTTIME/g;   # optimize ?

# use NOLINK (-c was found) or LINK TO ?
!s/\s+-E/ PPONLY/g && !s/\s+-c/ NOLINK/g && s/OBJNAME/LINK TO/;

# build amigaos command-line with extra defs
$_ = "sc IDIR=$LNDIR$_ DEF=__GNU_LIBRARY__ DEF=AMIGA DEF=_OFF_T DEF=off_t=long DATA=FAR CODE=FAR PARAM=B NOSTKCHK NOICON NOVERBOSE IGN=64,84,85,93,100,181,306,315,316 BATCH";
#$_ = "sc IDIR=$LNDIR$_ DEF=AMIGA DEF=_OFF_T DEF=off_t=long DATA=FAR CODE=FAR PARAM=B NOSTKCHK NOICON NOVERBOSE IGN=64,84,85,93,100,181,306,315,316 BATCH";

# if -d is present, display the executed command-line
s/\s+-d//g && print STDERR "=> $_\n";

# call SAS/C
$res = system("$_")/256;

# Link failed, say something so that configure script can
# see it.
if($res == 3) {print STDERR "link failed\n";$res=21;}

exit $res;
