#!/usr/bin/env ruby

unless (password = ARGV[0]) && (package = ARGV[1])
  STDERR.puts 'Usage: sign-rpm PASSWORD PACKAGE'
  exit 1
end

require 'pty'

rpm_cmd = "rpm --addsign #{package}"

puts rpm_cmd
PTY.spawn(rpm_cmd) do |r, w, pid|
  prompt = r.read(19)

  # match the expected prompt exactly, since that's the only way we know if
  # something went wrong.
  unless prompt == 'Enter pass phrase: '
    STDERR.puts "unexpected output from `#{rpm_cmd}`: '#{prompt}'"
    Process.kill(:KILL, pid)
    exit 1
  end

  STDOUT.puts prompt
  w.write("#{password}\n")

  # Keep printing output unti the command exits
  loop do
    begin
      line = r.gets
      puts line
      if line =~ /failed/
        STDERR.puts 'RPM signing failure'
        exit 1
      end
    rescue Errno::EIO
      break
    end
  end
end
