#!/usr/local/cpanel/3rdparty/bin/perl
package scripts::PopulateMailUserDirectory;

# cpanel - /opt/cpanel-ccs/bin/populate_mailuser_directory_for_ccs
#                                                   Copyright 2019 cPanel, L.L.C.
#                                                            All rights Reserved.
# copyright@cpanel.net                                          http://cpanel.net
# This code is subject to the cPanel license.  Unauthorized copying is prohibited

use strict;
use warnings;
no warnings 'experimental::signatures';

use feature 'signatures';

use lib '/var/cpanel/perl';
use Cpanel::CCS::Userdata ();

our $ACCOUNTS_XML = '/opt/cpanel-ccs/conf/auth/cpanel-accounts.xml';
our $TLS_DIR = '/opt/cpanel-ccs/conf/domain-TLS/';

our %SUBS = (
    '--import-accounts' => sub($check) {
        return if( $check && -s $ACCOUNTS_XML );
        return Cpanel::CCS::Userdata::output_xml(Cpanel::CCS::Userdata::create_directory());
    },
    '--import-tls'      => sub($check) {
        return if( $check && -d $TLS_DIR );
        require Cpanel::ServerTasks;
        Cpanel::ServerTasks::schedule_task( [ 'CCSTasks' ], 5, 'import_tls_data_for_ccs' );
        print "[INFO] Scheduled task to import TLS data into CCS.\n";
        return;
    },
);

=head1 USAGE

    populate_mailuser_directory_for_ccs [--import-accounts] [--import-tls] [--only-if-missing] [--help]

=head2 FLAGS

=over

=item --import-accounts

Whether or not to sync account status for CCS based on cPanel userdata.

=item --import-tls

When passed, the script will import TLS certificates for domains to
/opt/cpanel-ccs/conf/domain-TLS in order to support SNI for user domains.

=item --only-if-missing

When passed, we will check whether 'first time' setup of account and/or TLS
data has already occurred, and skip those steps if they appear to have
already been done.

=item --help

You are looking at it!

=back

=cut

sub script(@flags) {
    my @opts = grep { my $opt = $_; grep { $_ eq $opt } @flags  } qw{--import-accounts --import-tls};
    help() if !@opts || grep { $_ eq '--help' } @flags;
    my $check = grep { $_ eq '--only-if-missing' } @flags;
    for ( @opts ) { $SUBS{$_}->($check) };
    return 0;
}

sub help {
    require Pod::Usage;
    Pod::Usage::pod2usage( "-sections" => "NAME|USAGE" );
}

exit script(@ARGV) unless caller;

1;
