#!/usr/bin/ruby
#
# send-hook-info.rb: test helper script that reads a hook info dump from
#                    a specified file and sends it to a specified command
#                    through a file descriptor (useful to test
#                    "apt-listbugs apt" without the need to invoke APT)
#
# Copyright (C) 2013       Google Inc
# Copyright (C) 2013-2014  Francesco Poli <invernomuto@paranoici.org>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License with
#  the Debian GNU/Linux distribution in file /usr/share/common-licenses/GPL-2;
#  if not, write to the Free Software Foundation, Inc., 59 Temple Place,
#  Suite 330, Boston, MA  02111-1307  USA
#

def usage
  $stderr.print "Usage: ", $0, " <file> <command>\n"
end

# parse command-line arguments
if ARGV.length != 2
  usage
  exit 1
end
file = ARGV[0]
command = ARGV[1]

# check whether the specified file actually exists
if ! FileTest.exist?(file)
  $stderr.print "Cannot find file \"#{file}\"\n"
  exit 2
end

read_fd, write_fd = IO.pipe

# this variable tells the child command (e.g.: apt-listbugs) which
# file descriptor to read from
ENV['APT_HOOK_INFO_FD'] = read_fd.to_i.to_s
puts "APT_HOOK_INFO_FD set to #{ENV['APT_HOOK_INFO_FD']}"

if Process.fork().nil?
  # the child
  write_fd.close
  exec command, read_fd=>read_fd
  read_fd.close
  exit 0
else
  # the parent
  read_fd.close
  begin
    open(file).each { |line|
      write_fd.puts "#{line}"
    }
  rescue Errno::EACCES
    $stderr.print "Cannot read from file \"#{file}\"\n"
    exit 3
  end
  write_fd.close
  Process.waitall
end


