###
### Script pro vytvareni novych uzivatelu na mailboxu
###


#!/usr/bin/perl

use strict;
use warnings;
use Config::Simple;
use IMAP::Admin; # libimap-admin-perl
use Net::LDAP;  # libnet-ldap-perl 
use Error qw(:try);
use Log::Log4perl qw(get_logger :levels);
use Data::Dumper;

# Logování
Log::Log4perl::init('cyrus_tools.conf');
# stupen logování
# Log::Log4perl->easy_init($INFO);
# instance loggeru
my $logger = Log::Log4perl->get_logger();

# Konfigurační soubor
my $config = new Config::Simple('cyrus_tools.conf');
my $tmp_dir = $config->param('tmp_dir');

# pripojeni a nacteni uzivatelu
my $ldap = Net::LDAP->new( "<>", onerror => 'die' ) || die "Cannot connect: $@"; $ldap->bind() or die "Cannot bind: $@";
my $imap = IMAP::Admin->new( 'Server' => '<>', 'Login' => '<>', 'Password' => '<>');


my @mailboxes_all = $imap->list("user.%");
# print count of mailboxes_all
my $count_mailboxes = @mailboxes_all;
# print Dumper(@mailboxes_all);
$logger->info("Count of mailboxes: $count_mailboxes");
print "Count of mailboxes: $count_mailboxes\n";
my @mailboxes = ();
my $filename3 = $tmp_dir . '/' . "all_users_access_vsb_cz";
open(my $lists_user, '<:encoding(UTF-8)', $filename3) or die "Could not open file '$filename3' $!";
chomp(my @lists_user = <$lists_user>);
close $lists_user;
my $count_lists_user = @lists_user;
$logger->info("Count of WSDL: $count_lists_user");
print "Count of WSDL: $count_lists_user\n";


# odstranění user. z názvu mailboxu a ulozeni do pole 
foreach (@mailboxes_all) {
    next unless (/user\./);
    my $login = $_; 
    $login =~ s/user\.//; 
    # $login =~ s/\s+$//;
    # $login =~ s/^\s+//;
    push @mailboxes, $login;
}

# porovnani seznamu uzivatelu a seznamu mailboxu vysledek bude rozdil mezi seznamy
my @diff = ();
foreach my $user (@lists_user) {
    my $found = 0;
    foreach my $mailbox (@mailboxes) {
        if ($user eq $mailbox) {
            $found = 1;
            last;
        }
    }
    if ($found == 0) {
        push @diff, $user;
    }
}

# print @diff;
my @diff_test = ("xxxxxx");

# print @diff_test."\n";
my $not_ldap = 0;
my $not_ldap_email = 0;

# print Dumper(@diff);

foreach (@diff){
    my $login = $_; 
    # print $login."\n";
    my $msg = $ldap->search(filter=>"(uid=$login)");
    # print $msg->count()."\n";
    if ($msg->count() == 0) {
        # $logger->warn("User not found atributtes in LDAP: $login");
	#print $login."\n";
	    $not_ldap= $not_ldap + 1;
        # print "-".$login;
        next;
    }
    foreach my $entry ( $msg->entries() ) {

        my $mailbox = "user." . $login;
        my $mailbox_sent = $mailbox . ".Sent";
        # my $mailbox_trash = $mailbox . ".Trash";
        # my $mailbox_junk = $mailbox . ".Junk";

        
        # kontrola zda je $mailbox v @mailboxes_all
        my $found_exist = 0;
        foreach my $mailbox_all (@mailboxes_all) {
            if ($mailbox eq $mailbox_all) {
                $found_exist = 1;
                last;
            }
        }

        if ($found_exist == 0) {
            # hlavni slozka
	    #print $mailbox;

            my $err = $imap->create($mailbox);
            if ($err != 0) {
                $logger->error("Error occurred building $mailbox\n\t$imap->{'Error'}");
            }
            $logger->info("Mailbox $mailbox created");

            # slozka pro odeslani
            my $err_sent = $imap->create($mailbox_sent);
            if ($err_sent != 0) {
                $logger->error("Error occurred building $mailbox_sent\n\t$imap->{'Error'}");
            }
            $logger->info("Mailbox $mailbox_sent created");  

            #####
            # # slozka pro smazane
            # my $err_trash = $imap->create($mailbox_trash);
            # if ($err_trash != 0) {
            #     $logger->error("Error occurred building $mailbox_trash\n\t$imap->{'Error'}");
            # }
            # $logger->info("Mailbox $mailbox_trash created");

            # # slozka pro spam
            # my $err_junk = $imap->create($mailbox_junk);
            # if ($err_junk != 0) {
            #     $logger->error("Error occurred building $mailbox_junk\n\t$imap->{'Error'}");
            # }
            # $logger->info("Mailbox $mailbox_junk created");
            ####

            # set acl
            $imap->set_acl($mailbox, $config->param('cyrus_admin'), 'lrswipkxtecda') or $logger->warn("Error setting ACL for $mailbox\n\t$imap->{'Error'}");
            $logger->info("Mailbox set ACL $mailbox lrswipkxtecda");

            # set quota
            foreach my $record ($entry->get_value("groupMembership")){
                if ($record =~ /<xxxx>/ || $record =~ /<yyyy>/) {
                        $imap->set_quota($mailbox, $config->param('staff_quota'));
                        $logger->info("Set quota ZAM: $mailbox");
                        last;
                    }
                else
                    {
                        $imap->set_quota($mailbox, $config->param('student_quota'));
                        $logger->info("Set quota STU: $mailbox");
                        last;
                    }
            }
        }
        else {
            $logger->warn("Mailbox $mailbox already exists");
        }

    }
}

# Získání informací o schopnostech serveru
#my $capabilities = $imap->{'Capability'};
#print "Schopnosti serveru: $capabilities\n"; # Použití hodnoty v kontextu printu

$ldap->unbind;
$imap->close;
print "Mailboxu without LDAP param $not_ldap\n";
$logger->info("Mailboxu without LDAP param $not_ldap");
print "Mailboxu without LDAP email param $not_ldap_email\n";
$logger->info("Mailboxu without LDAP email param $not_ldap_email");
