#!/usr/bin/env ruby

require 'optparse'

timeout = [12*60+30, 18*60+00].map { |timeout|
  now = Time.now
  timeout - (now.hour*60 + now.min)
}.find(60*60) {|timeout| timeout > 0 }
timeout = timeout.divmod(60).zip(%w[ h m ]).map(&:join).join

OptionParser.new do |opts|
  opts.banner = "Usage: #{__FILE__} [options]"

  opts.on("-tTIMEOUT", "--t=TIMEOUT",
          "Default timeout: #{timeout}") { |t| timeout = t }
end.parse!

def with_mount(image)
  out = `hdiutil mount "#{image}"`
  mountpoint = out.split(/\s+/).last
  yield mountpoint
ensure
  puts `hdiutil detach "#{mountpoint}"`
end

keyz = File.expand_path("../keyz.sparsebundle", __FILE__)
with_mount(keyz) do |mountpoint|
  `ssh-add -t #{timeout} "#{File.join(mountpoint, "id_rsa")}"`
end
# `hdiutil eject "#{File.dirname(__FILE__)}"`