#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - autofixer2/remove-inbox-inbox             Copyright 2018 cPanel, Inc.
#                                                           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;

use Cpanel::AccessIds::ReducedPrivileges ();
use Cpanel::Config::Users                ();
use Cpanel::Email::Accounts              ();
use Cpanel::PwCache                      ();
use File::Path                           ();

exit main() unless caller;

sub note {
    my ($msg) = @_;
    print "$msg\n";
    return 0;
}

sub fix_user {
    my ($user)  = @_;
    my $homedir = Cpanel::PwCache::gethomedir($user);
    my $privs   = Cpanel::AccessIds::ReducedPrivileges->new($user);
    my $accounts = Cpanel::Email::Accounts::manage_email_accounts_db( event => 'fetch', no_disk => 1 );
    my @paths = map {
        my $domain = $_;
        map { "$homedir/mail/$domain/$_" } keys %{ $accounts->{$domain}{'accounts'} }
    } keys %$accounts;
    foreach my $path ( "$homedir/mail", sort @paths ) {
        note("  Checking $path");
        opendir( my $dh, $path ) or next;
        my @dirs = grep { /\A\.INBOX(?:\.|\z)/ && -d "$path/$_" } readdir($dh);
        closedir($dh);
        foreach my $dir (@dirs) {
            note("    Removing $path/$dir");
            File::Path::rmtree("$path/$dir");
        }
    }
    return 1;
}

sub main {
    my @users = Cpanel::Config::Users::getcpusers();
    foreach my $user ( sort @users ) {
        note("Checking user $user...");
        eval { fix_user($user); } or warn "$@";
    }
    return 0;
}
