#!/usr/bin/env ruby

unless (rpm_cmd = ARGV[0])
  STDERR.puts 'Usage: sign-rpm RPM_COMMAND'
  exit 1
end

password = '<%= passphrase %>'

require 'pty'

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/) && !(line =~ /warning:/)
        STDERR.puts 'RPM signing failure'
        exit 1
      end
    rescue Errno::EIO
      break
    end
  end
end
