#!/usr/bin/perl -w

use esmith::ConfigDB;
use esmith::DomainsDB;
my $c = esmith::ConfigDB->open_ro  || die "Couldn't open the configuration database";
my $d = esmith::DomainsDB->open_ro || die "Couldn't open the domains database";
my $domain = shift || $c->get('DomainName')->value;

die "Domain $domain doesn't exist"
  unless ($d->get($domain) && $d->get($domain)->prop('type') eq 'domain');

warn "DKIM Signing is disabled for domain $domain"
  if (($d->get($domain)->prop('DKIMSigning') || 'enabled') eq 'disabled');

die "Can't find DKIM keys for domain $domain"
  unless (-e "/var/service/qpsmtpd/config/dkim/$domain/public");

die "Can't find the selector for domain $domain"
  unless (-e "/var/service/qpsmtpd/config/dkim/$domain/selector");

print <<'_EOF';

Here are sample DNS entries you should add in your public DNS
The DKIM entry can be copied as is, but others will probably need to be adjusted
to your need. For example, you should either change the reporting email adress
for DMARC (or create the needed pseudonym)

_EOF

my $key_string = "v=DKIM1;p=";
open PUBKEY, "/var/service/qpsmtpd/config/dkim/$domain/public";
while(<PUBKEY>){
  next if /^\-/;
  chomp;
  $key_string .= $_;
}
close PUBKEY;
$key_string .= ";t=y";
open SEL, "/var/service/qpsmtpd/config/dkim/$domain/selector";
my $selector = <SEL>;
chomp $selector;
close SEL;

my @key_chunks = ( $key_string =~ /.{1,255}/g );
my $txt = '';
$txt .= '"' . $_ . '"' foreach (@key_chunks);

print <<"_EOF";

$selector._domainkey IN TXT $txt
\@ IN SPF "v=spf1 mx a -all"
\@ IN TXT "v=spf1 mx a -all"
_dmarc IN TXT "v=DMARC1; p=none; adkim=s; aspf=r; rua=mailto:dmarc-feedback\@$domain; pct=100"

_EOF
