# -*- ruby -*-

def restrict_accounts_generic(options, &restricted_account_p)
  condition_name = options[:condition_name] || "Restrict Accounts"
  milters = options[:milters] || defined_milters
  define_applicable_condition(condition_name) do |condition|
    condition.description = "Restrict milters to specified accounts"

    condition.define_envelope_recipient_stopper do |context, recipient|
      if restricted_account_p.call(context, recipient)
        false
      else
        context["have-not-restricted-account"] = "true"
        true
      end
    end

    condition.define_data_stopper do |context|
      context["have-not-restricted-account"] == "true"
    end
  end

  milters.each do |milter_name|
    define_milter(milter_name) do |milter|
      milter.applicable_conditions += [condition_name]
    end
  end
end

def restrict_accounts_by_list(*accounts)
  if accounts.last.is_a?(Hash)
    options = accounts.pop.dup
  else
    options = {}
  end
  options[:condition_name] ||= "Restrict Accounts by List: #{accounts.inspect}"
  restrict_accounts_generic(options) do |context, recipient|
    if /\A<(.+)>\z/ =~ recipient
      address = $1
    else
      address = recipient
    end
    accounts.any? {|account| account === address}
  end
end
