#!perl
use Config;

$libdir = $ENV{PERL_SRC} || "$Config{installarchlib}/CORE";

my $quiet++ if $ARGV[0] eq '-q';
shift if $quiet;
my $debug++ if $ARGV[0] eq '-d';
shift if $debug;

if (grep(/^-[cES]$/, @ARGV)) { # compile-only with -c -E or -S
    ;
} elsif (grep(/^-Bdynamic$/, @ARGV)) { # force dynamic linking with -Bdynamic
    use ExtUtils::Embed;
    @ARGV = grep{ !/^-Bdynamic$/o } @ARGV;
    $linkargs = ldopts;
} elsif ( -e "$libdir/$Config{libperl}" and $Config{libperl} !~ /\.(dll|so)$/ ) {
    # prefer static linkage
    $linkargs = sprintf("%s $libdir/$Config{libperl} %s",
		        @Config{qw(ldflags libs)});
} else { # try dynamic lib if no static lib exists
    use ExtUtils::Embed;
    @ARGV = grep{ !/^-Bdynamic$/o } @ARGV;
    $linkargs = ldopts('-std');
}

sub cc_harness_msvc {
    my @ARGV = @_;
    use ExtUtils::Embed ();
    my $obj = "${Output}.obj";
    my $compile = ExtUtils::Embed::ccopts." -c -Fo$obj @ARGV ";
    my $link = "-out:$Output $obj";
    $compile .= " -I".$_ for split /\s+/, opt(I);
    $link .= " -libpath:".$_ for split /\s+/, opt(L);
    # TODO: -shared,-static,-sharedxs,-staticxs
    if ($stash) {
        my @mods = split /-?u /, $stash;
        $link .= " ".ExtUtils::Embed::ldopts("-std", \@mods);
    } else {
        $link .= " ".ExtUtils::Embed::ldopts("-std");
    }
    $link .= " perl5$Config{PERL_VERSION}.lib kernel32.lib msvcrt.lib";
    print "running $Config{cc} $compile" unless $quiet;
    system("$Config{cc} $compile");
    print "running $Config{ld} $link" unless $quiet;
    system("$Config{ld} $link");
}

if ($^O =~ m/^MSWin/ && $Config{cc} =~ m/^cl/i) {
  cc_harness_msvc(@ARGV);
  exit;
}

# ActivePerl 5.10.0.1004 claims to use MSVC6 but used MSVC8
#if ($Config::Config{ccversion} eq '12.0.8804' and $Config::Config{cc} eq 'cl') {
#  $linkargs =~ s/ -opt:ref,icf//;
#}

my $ccflags = $Config{ccflags};
$ccflags .= " -ansi -pedantic -Wall -Wextra -Wconversion -Wshadow -Wcast-qual -Wwrite-strings"
  if $debug and $Config{cc} =~ /gcc/;

$cccmd = "$Config{cc} $ccflags -I$libdir @ARGV $linkargs";
print "$cccmd\n" unless $quiet;
exec $cccmd;
