#
# Perl script being a wrapper around the gnu ld. When a dll is specified to
#   to be built, special processing is done, else the standard ld is called.
#

# theese are pretty mandatory
my $CC = '@CC@';
my $DLLWRAP = '@DLLWRAP@';

# following are optional.
my $WRAPDRIVER = '@WRAPDRIVER@';
my $AS = '@AS@';
my $DLLTOOL = '@DLLTOOL@';
my $EXPORT_ALL = @EXPORT_ALL@;
# if some of extensions are undefined,
# no corresponding output will be done.
# most probably, you'd like to have an export library
my $DEF_EXT = '@DEF_EXT@';
# my $EXP_EXT = '@EXP_EXT@';
my $LIB_EXT = '@LIB_EXT@';

#my $DEBUG ="perlld.out";
my $DEBUG =undef;

my $args = join(" ",@ARGV); # get args
my $verbose =grep(/^\-(v|\-verbose)$/, @ARGV);

sub shellexec;

if ($DEBUG) {
  open DEBUGFILE, ">>$DEBUG";
  print DEBUGFILE "\n--- " .localtime() ."\nargs:\n$args\n\nenvironment:\n";
  foreach (keys(%ENV)) { print DEBUGFILE $_, "=", $ENV{$_}, "\n"; };
}

if ($args !~ /\-o (\S+)/) {
  print DEBUGFILE "+ no dll output -- passing to gcc\n\n" if $DEBUG;
  shellexec("$CC $args\n");
} else {
  my ($path, $command, $dllname, $libname) ='';

  $dllname =$1;
  print DEBUGFILE "output file: $dllname\n" if $DEBUG;
  # remove -o from args
  $args =~ s/(^| )\-o \S+/$1/;

  # Check for path:
  if( $dllname =~ /.*[\/\\]/){
    $dllname = $';
    $path = $&;
    $path =~ s,[/\\](\.[/\\])*,/,g;
  }
  if ($dllname =~ /\./) { $libname =$`; } else { $libname =$dllname; };
  $dllname ="$libname.dll";
  $libname ="lib$libname" unless ($libname =~ /^lib/);
  print DEBUGFILE "dll name: $dllname\nimport library: $libname\npath: $path\n" if $DEBUG;

  $command ="$DLLWRAP --dllname $dllname";
  $command .=" --driver-name $WRAPDRIVER" if $WRAPDRIVER;
  $command .=" --dlltool $DLLTOOL" if $DLLTOOL;
  $command .=" --export-all-symbols" if $EXPORT_ALL;
  $command .=" --as $AS" if $AS;
  $command .=" --verbose" if $verbose;

  $command .=" --output-def $libname$DEF_EXT" if $DEF_EXT;
  $command .=" --output-exp $libname$EXP_EXT" if $EXP_EXT;
  $command .=" --output-lib $libname$LIB_EXT" if $LIB_EXT;

  # other args are passed through
  shellexec("$command \\\n$args\n");

  if ($path) {
    $command ="mv $dllname";
    $command .=" $libname$LIB_EXT" if $LIB_EXT;
    shellexec("$command $path\n");
  };
};
close DEBUGFILE if $DEBUG;

#---------------------------------------------------------------------------
sub shellexec{
  my $command =shift;
  print $command;
  print DEBUGFILE $command if $DEBUG;
  system($command) == 0
    or die "perlld: *** system() failed to execute\n$command\n";
};

1;
