<%

require 'digest/md5'
require 'expect'
require 'tempfile'


config = {}
config['cachedir'] = '/var/cache/puppet'
config['kadmin'] = '/usr/bin/kadmin'
config['klist'] = '/usr/bin/klist'


# set global vars
cachefile = File.join(config['cachedir'],
		      homename + '.' + Digest::MD5.hexdigest(name))

# function to check if keytab contains required principals
def check_keytab(config, keytab, principals)
  entries = []
  IO.popen(sprintf('%s -k %s', config['klist'], keytab), mode='r') { |f|
    f.readlines.each do |l|
      next unless l =~ /[ ]+\d+ .*/
      entries << l.split()[1]
    end
  }
  principals.each do |p|
    if not entries.include?(p)
      return false
    end
  end
  return true
end


# check if we have cached keytab up to date
cached = true
if File.exists?(cachefile)
  if not check_keytab(config, cachefile, principals)
    cached = false
    File.unlink(cachefile)
  end
else
  cached = false
end

# create new keytab if cache is not up to date
if not cached
  cmd = sprintf('%s -p %s -k -t /etc/puppet/puppet.keytab -q "ktadd -k %s %s"',
      config['kadmin'], kerberos_user, cachefile, principals.join(' '))
  output = `#{cmd} 2>&1`
  if not File.exists?(cachefile)
    raise 'Failed to create keytab ' + name + ' error was: ' + output
  elsif not check_keytab(config, cachefile, principals)
    raise 'Invalid keytab ' + name + ' created'
  end
end

# read keytab into memory
data = File.open(cachefile).read

-%><%= data -%>
