#!/usr/local/cpanel/3rdparty/bin/perl

=head1 NAME

syncssl - list or sync domains with recently-acquired certs

=head1 SYNOPSIS

    syncssl [--days=<days>] [--dry-run] [-jitter=<seconds>]

    # As a cron:
    15  4   *   *   *   root /usr/local/cpanel/bin/eig/syncssl --jitter=3600

=head1 OPTIONS

=over

=item * --days=<days>

Search for certificates no more than this many days old.

=item * --dry-run

Don't actually do anything, just print to C<STDOUT> what would be done.

=item * --jitter=<seconds>

Sleep for a given amount of seconds (useful when running in a cron).

=back

=cut

use warnings;
use strict;

use EIG::HP::SyncSSL qw(sync_domains_to_hp domain_list record_domains);
use Getopt::Long;
use IPC::Open2;
use JSON qw(decode_json);
use Pod::Usage;

main();
exit;

sub main {
    my $dry_run = 0;
    my $jitter  = 0;
    my $days    = 10;

    GetOptions(
        'dry-run!'  => \$dry_run,
        'jitter=i'  => \$jitter,
        'days=i'    => \$days,
    ) or pod2usage(2);

    my $now     = time;
    my $cutoff  = $now - $days * 86400;

    my %domains = map { $_ => 1 } domains_with_new_certs($cutoff);

    my $domain_list;

    if (keys %domains) {
        $domain_list = domain_list();

        # skip domains that have already been synced within the period we're looking at
        for my $domain (keys %domains) {
            my $info = $domain_list->lookup($domain);
            delete $domains{$domain} if $info && $cutoff < $info->{'last_synced'};
        }
    }

    my @domains = keys %domains;

    if ($dry_run) {
        if (@domains) {
            print 'DRY RUN: Would have synced domains:', "\n", join("\n", @domains), "\n";
        }
        else {
            print 'DRY RUN: No domains to sync.', "\n";
        }
        exit;
    }

    if ($jitter) {
        my $seconds = int(rand($jitter));
        local $0 = "syncssl: Sleeping for $seconds seconds (jitter)";
        sleep($seconds);
    }

    my $results = sync_domains_to_hp(\@domains);

    my @synced_domains = map { $_->{'status'} ne 'fail' ? $_->{'domain'} : () } @$results;
    record_domains(\@synced_domains, list => $domain_list, time => $now);
}

### List domains that have new certificates (with "not before" dates after $time).
#   @domains = domains_with_new_certs($from, $to);
sub domains_with_new_certs {
    my $cutoff_lower = shift;
    my $cutoff_upper = shift || (time + 86400 * 5);

    my %domains;

    for my $certpath (glob('/var/cpanel/ssl/installed/certs/*.crt')) {
        my $info = eval { read_certificate($certpath) };
        warn $@ if $@;
        next if !$info;

        my $not_before = $info->{'not_before'};

        next if $not_before < $cutoff_lower || $cutoff_upper < $not_before;

        for my $domain (@{$info->{'domains'}}) {
            $domains{$domain}++;
        }
    }

    return keys %domains;
}

### Read the domains and notBefore from a certificate.
#   $info = read_certificate($filepath);
sub read_certificate {
    my $certfile = shift;

    # try the cache first
    my $cachefile = "${certfile}.cache";
    my $cache = eval {
        open(my $fh, '<', $cachefile) or die "open cache '$cachefile' failed: $!";
        local $/;
        decode_json(<$fh>);
    };
    # ignore cache errors

    my %info;

    if ($cache) {
        $info{'domains'}    = $cache->{'parsed'}->{'domains'};
        $info{'not_before'} = $cache->{'parsed'}->{'not_before'};
    }

    return \%info if $info{'domains'};

    my $pid = open2(my $fh, undef, qw{openssl x509 -text -in}, $certfile) or die "openssl error: $!";

    my %domains;

    while (defined (my $line = <$fh>)) {
        $line =~ s{^\s+}{};
        $line =~ s{\s+$}{};

        if ($line =~ m{^Subject:.*?CN=(.*)}) {
            $domains{$1}++;
        }
        elsif ($line =~ m{Not Before: ([A-Za-z0-9 :]+ GMT)}) {
            $info{'not_before'} = datetime_to_unix($1);
        }

        my @san = $line =~ m{DNS:([^,]+)};
        for my $san (@san) {
            $domains{$san}++;
        }
    }

    waitpid($pid, 0);

    $info{'domains'} = [keys %domains] if keys %domains;
    $info{'domains'} or die "Failed to find any domains on cert '$certfile'\n";

    return \%info;
}

### Convert a datetime to UNIX epoch.
#   $unix_time = datetime_to_unix('Apr 23 19:28:34 2018 GMT');
sub datetime_to_unix {
    my $date = shift;
    return `date --date='$date' +%s`;
}

