#!/usr/bin/perl -w
#$Id: as,v 1.11 2005/02/19 05:55:31 hchen Exp $

use strict;
use File::Basename;
use Getopt::Long qw(:config gnu_compat bundling_override pass_through);
use File::Temp qw/ tempfile tempdir /;
use FileHandle;
use lib dirname($0) . "/../lib";
use Util;

setLogFile($ENV{MOPS_LOG});
begin();

## Make sure we can get everything we need from the environment
my ($MOPS_ENABLE, $MOPS_TEMPDIR, $MOPS_GCC_AS, $MOPS_OBJCOPY);
foreach my $var (qw(MOPS_ENABLE MOPS_TEMPDIR MOPS_GCC_AS MOPS_OBJCOPY))
{
  if (! defined($ENV{$var}))
  {
    info("Environment variable $var not set, skipping\n");
    end(1);
  }
  eval "\$$var = \"$ENV{$var}\"";
  debug("$var set to ", eval("\$$var"), "\n");
}
if (!$MOPS_ENABLE)
{
  end(runSysCmd($MOPS_GCC_AS, @ARGV));
}

## Parse command-line options
my ($inputFile, $outputFile, $isInputStdin, $unused, @savedARGV, $fh, $str,
    $ret);
@savedARGV = @ARGV;
GetOptions("a:s" => \$unused,
   "D|f|K|L|R|statistics|W|warn|no-warn|fatal-warnings|x|Z|Qy|V" => \$unused,
	   "I=s" => \$unused,
	   "o=s" => \$outputFile);

$inputFile = getInputFileName(\@ARGV);
if ($inputFile eq "-")
{
  $isInputStdin = 1;
  (undef, $inputFile) = tempfile($MOPS_TEMPDIR . "/stdin-XXXX", SUFFIX => ".s",
				 UNLINK => 1);
  $fh = new FileHandle ">$inputFile" or do
    { error("Cannot open $inputFile for writing\n"); end(1) };
  while (defined($str = <STDIN>))
  {
    print $fh $str;
  }
  $fh->close();
}
else
{
  $isInputStdin = 0;
}
$outputFile = "a.out" unless defined($outputFile);

# Run the real as
if (!$isInputStdin)
{
  $ret = runSysCmd($MOPS_GCC_AS, @savedARGV);
}
else
{
  $ret = runSysCmd($MOPS_GCC_AS, @savedARGV, { STDIN => $inputFile });
}
if ($ret != 0)
{
  end($ret);
}
if (!-f $outputFile)
{
  info("Output file $outputFile does not exist.\n");
  end(1);
}

#testing only!
#link($inputFile, "$inputFile.tmp");
#info("saving $inputFile.tmp\n");
#link($outputFile, "$outputFile.tmp");
#info("saving $outputFile.tmp\n");

# Find the CFG file
my ($cfgFile);
$fh = new FileHandle $inputFile or do
{ error("Cannot open $inputFile for reading\n"); end(1); };
$str = <$fh>;
$fh->close();
if ($str =~ /^#MOPSCFG:\s*(\S+)/)
{
  $cfgFile = $1;
  if ((!-f $cfgFile) || (-z $cfgFile))
  {
    info("The CFG file $cfgFile does not exist or is empty\n");
    end(1);
  }
}
else
{
  info("The assembly file $inputFile does not contain a CFG.\n");
  end(0);
}

## Now we're ready to attach the CFG to the .o file
my @objCmd = ($MOPS_OBJCOPY,
	      "--add-section", ".MOPS=" . $cfgFile,
	      "--set-section-flags", ".MOPS=contents,load,alloc",
	      $outputFile);
if (($ret = runSysCmd(@objCmd)) != 0)
{
  end($ret);
}

end(0);

