#!/usr/bin/env ruby
# Wrapper around the real `as` which adds filtering capabilities.

require "tempfile"
require "fileutils"

def wrapped_as(argv)

  args=[]
  input=nil

  i = 0
  while i<argv.size
    case argv[i]
    when "-o", "-I"
      args.push(argv[i])
      args.push(argv[i+1])
      i = i + 1
    when /^-/
      args.push(argv[i])
    else
      if input
        exit 1
      else
        input = argv[i]
      end
    end
    i = i + 1
  end

  if input==nil
    # We dont handle pipe yet:
    exit 1
  end

  # Generate temp file
  tempfile = Tempfile.new("as-filter")
  tempfile.close
  script = File.dirname($0) + "/clean-stack-filter"
  unless system([script, script], 0 => input, 1 => tempfile.path)
    status=$?.exitstatus
    FileUtils.rm tempfile
    exit status
  end
  args.push(tempfile.path)

  # Call the real assembler:
  res = system("as", *args)
  status = if res != nil
             $?.exitstatus
           else
             1
           end
  FileUtils.rm tempfile
  exit status

end

wrapped_as(ARGV)
