#!/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 IO::Select;
use IPC::Open2;
use JSON qw(decode_json encode_json);
use Pod::Usage;

main();
exit;

sub describe {
    return [{
        category        => 'Whostmgr',
        event           => 'AutoSSL::installssl',
        stage           => 'post',
        hook            => '/usr/local/cpanel/bin/eig/syncssl --hook=autossl',
        exectype        => 'script',
        escalateprivs   => 1,
    }, {
        category        => 'Whostmgr',
        event           => 'SSL::installssl',
        stage           => 'post',
        hook            => '/usr/local/cpanel/bin/eig/syncssl --hook=whm',
        exectype        => 'script',
        escalateprivs   => 1,
    }, {
        category        => 'Cpanel',
        event           => 'API1::SSL::install',
        stage           => 'post',
        hook            => '/usr/local/cpanel/bin/eig/syncssl --hook=api1',
        exectype        => 'script',
        escalateprivs   => 1,
    }, {
        category        => 'Cpanel',
        event           => 'API2::SSL::installssl',
        stage           => 'post',
        hook            => '/usr/local/cpanel/bin/eig/syncssl --hook=api2',
        exectype        => 'script',
        escalateprivs   => 1,
    }, {
        category        => 'Cpanel',
        event           => 'UAPI::SSL::install_ssl',
        stage           => 'post',
        hook            => '/usr/local/cpanel/bin/eig/syncssl --hook=uapi',
        exectype        => 'script',
        escalateprivs   => 1,
    }];
}

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

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

    if ($describe) {
        print encode_json(describe());
        return;
    }

    my $now = time;
    my @domains = $hook ? hook(hook => $hook) : scan(days => $days, now => $now);

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

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

    # TODO - Switch to syncing to HAL callback tower sometime before HP is gone.
    my $results = sync_domains_to_hp(\@domains, $hook ? (timeout => 15) : ());

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

    print @synced_domains ? '0 Domain synced.' : '0 Domain did not sync.' if $hook;
}

sub scan {
    my %args = @_;
    my ($days, $now) = @args{qw(days now)};

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

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

    if (keys %domains) {
        my $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'};
        }
    }

    return keys %domains;
}

sub hook {
    my $input = get_passed_data();

    return () if defined $input->{'result'} && $input->{'result'}->{'status'} != 1;

    my $data = $input->{'data'};
    my $domain = $data->{'domain_set_name'};    # Whostmgr::AutoSSL::installssl
    $domain ||= $data->{'domain'};              # Whostmgr::SSL::installssl et al.
    $domain ||= $input->{'result'}->{'domain'};

    return () if !$domain || !can_sync_domain($domain);
    return ($domain);
}

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

    my %domains;

    my @cert_files = (
        glob('/var/cpanel/ssl/apache_tls/*/combined'),
        glob('/var/cpanel/ssl/installed/certs/*.crt'),  # old location
    );

    for my $certpath (@cert_files) {
        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'}}) {
            next if !can_sync_domain($domain);
            $domains{$domain}++;
        }
    }

    return keys %domains;
}

### Read the domains and notBefore from a certificate.
#   $info = read_certificate($filepath);
# TODO - Use GT.
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;
}

sub can_sync_domain {
    my $domain = shift;
    my $skip = $domain =~ /^(?:autodiscover|cpanel|cpcalendars|cpcontacts|mail|webdisk|webmail|www)\./;
    return !$skip;
}

### 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`;
}

# Process data from STDIN.
sub get_passed_data {
    # Declare input variables.
    my $raw_data   = '';
    my $input_data = {};

    # Set up an input object.
    my $selects    = IO::Select->new();

    # Get input from STDIN.
    $selects->add(\*STDIN);

    # Process the raw output, and JSON-decode.
    if ($selects->can_read(.1)) {
        while (<STDIN>) {
            $raw_data .= $_;
        }
        $input_data = decode_json($raw_data);
    }

    # Return the output.
    return $input_data;
}

