#! /usr/bin/ruby -w
# addkeys - fancy way to run ssh-add multiple times
#

require 'pty'
require 'expect'
require 'readline'

class AddKeys
  include Readline

  def initialize
    if !ENV['SSH_AGENT_PID']
      puts 'ssh-agent is not running.  exiting'
      exit 1
    end
    @keys = ARGV.collect { |fname| File.expand_path(fname) }
    @passwd = nil
    if @keys.length > 0
      @passwd = readline('password please:  ', false)
      puts ''
    end
  end

  def run
    @keys.each { |keyfile|
      puts "adding key: #{keyfile}"
      PTY.spawn("ssh-add #{keyfile}") do |rfh,wfh,pid|
	wfh.sync = true

	rfh.expect(/^Enter passphrase for .*: /) {
	  wfh.puts @passwd
	}
	loop {
	  begin
	    match = rfh.expect(/^Bad passphrase, try again: /, 1)
	  rescue		# child may have exited, meaning success
	    break
	  end
	  @passwd = readline(match[0].sub(/^\s+/, ''), false)
	  puts ''
	  wfh.puts @passwd
	}
      end
    }
  end
end

begin
  system "stty -echo"
  AddKeys.new.run
  system "ssh-add -l"
ensure
  system "stty echo"
end
