require 'open3'
#
# Access username and password from mac os x keychain
#
# Author: Thomas Flemming (thomasfl at usit dot uio dot no) 2009
#
# synposis
#
# read_password www.webdav.org
# userame: tiger
# password: scott
#
# To add username and password to you keychain
#
# 1. Go to a webpage protected with http(s) authentication
# 2. Type in username and password, and check the
# box for adding username and password to keychain
# 3. Run this script.
# 4. A Keychain dialog windows should appear. Click
# on the button to allow access to the program "security".
#
# User Keychain Access to remove privilegies, username or passwords
# from keychain.
#
def decode_hex_string(hex_str)
str = ""
i = true
hex_str.split("").each do | char |
if(i)
str += char
i = false
else
str += char + " "
i = true
end
end
decoded_str = ""
str.split(' ').each do |val|
decoded_str += val.hex.chr
end
return decoded_str
end

def fetch_keychain_password(server)
command = "security find-internet-password -g -s " + server
username = nil
password = nil

Open3.popen3(command) do |stdin, stdout, stderr|
stderr = stderr.readlines.join("")
stderr=~ /^password: "(.*)"$/
password = $1

if(!password)
stderr=~ /^password: (0x.*)$/
password = $1
if(password)
password = decode_hex_string( password.sub(/^0x/,"") )
end
end
stdout = stdout.readlines.join("")
stdout =~ /"acct"[^=]*="(.*)"/
username = $1

end
return [username, password]
end

host = ARGV[0]
if(!host)
puts "read_password: error: missing hostname"
puts "read_password: usage read_password hostname"
exit
end
result = fetch_keychain_password(host)
if(result[0])
puts "Username:" + result[0]
puts "Password:" + result[1]
else
puts "Username and password not set for " + host
puts "[Instructions for adding username and password for "
puts "to server with Safari and Keychain...]"
end