#!/usr/bin/env ruby1.8
#
# This script checks all public keys in the keyring of the given schleuder-list
# for being expired (or otherwise unusable) and reports the output (if there
# was something found) to the list-admins.
# Key are being reported if they expire within the next 14 days.
# We suggest to run this script from cron once a week.

$VERBOSE = nil

require 'schleuder'
include Schleuder

if ARGV.size != 1
  puts "Usage: #{File.basename(__FILE__)} listname"
  exit 1
elsif ! File.directory?(List.listdir(ARGV.first))
  puts "No such list: '#{ARGV.first}'."
  exit 1
end

listname = ARGV.first
Schleuder.list = List.new(listname)

now = Time.now
checkdate = now + (60 * 60 * 24 * 14) # two weeks
crypt = Crypt.new('')
msg = ''
unusable = []
expiring = []

crypt.list_keys.each do |key|
  if (exp = key.subkeys.first.expires) > Time.utc(1971, 1, 1, 1)
    # key has expiry date
    if now < exp && exp < checkdate
      # key expires in the near future
      expdays = ((exp - now)/86400).to_i
      expiring << [key, expdays]
    end
  end

  if not (trust = [:revoked, :expired, :disabled, :invalid].grep(key.trust)).empty?
    unusable << [key, trust]
  end
end

expiring.each do |key,days|
  msg << "-> Key expires in #{days} days:\n#{key.to_s}\n\n"
end

unusable.each do |key,trust|
  msg << "-> Key is #{trust.join(' and ')}:\n#{key.to_s}\n"
end

unless msg.empty?
  prefix = "Checking the public keys present in the keyring of list #{listname} for usability gave the following result:".fmt(72)
  Schleuder.log.notify_admin('keys', prefix + "\n\n" + msg)
end

