use strict;
use warnings;

our @Initial = (
    sub {
        RT->Logger->debug('Removing all delegated rights');

        my $acl = RT::ACL->new(RT->SystemUser);
        $acl->Limit( CLAUSE   => 'search',
                     FIELD    => 'DelegatedBy',
                     OPERATOR => '>',
                     VALUE    => '0'
                   );
        $acl->Limit( CLAUSE          => 'search',
                     FIELD           => 'DelegatedFrom',
                     OPERATOR        => '>',
                     VALUE           => '0',
                     ENTRYAGGREGATOR => 'OR',
                   );

        while ( my $ace = $acl->Next ) {
            my ( $ok, $msg ) = $ace->Delete();

            if ( !$ok ) {
                RT->Logger->warn(
                           "Unable to delete ACE " . $ace->id . ": " . $msg );
            }
        }

        my $groups = RT::Groups->new(RT->SystemUser);
        $groups->Limit( FIELD    => 'Domain',
                        OPERATOR => '=',
                        VALUE    => 'Personal',
                        CASESENSITIVE => 0,
                      );
        while ( my $group = $groups->Next ) {
            my $members = $group->MembersObj();
            while ( my $member = $members->Next ) {
                my ( $ok, $msg ) = $group->DeleteMember( $member->MemberId );
                if ( !$ok ) {
                    RT->Logger->warn(   "Unable to remove group member "
                                       . $member->id . ": "
                                       . $msg );
                }
            }
            $group->PrincipalObj->Delete;
            $group->RT::Record::Delete();
        }
    },
);

