use strict;
use warnings;

our @Initial = (
    sub {
        RT->Logger->debug(
            'Going to update empty Queue Lifecycle column to "default"');

        my $queues = RT::Queues->new( RT->SystemUser );

        # override the default order by SortOrder, because it doesn't exist yet
        $queues->OrderByCols();

        $queues->FindAllRows;
        $queues->Limit(
            FIELD    => 'Lifecycle',
            OPERATOR => 'IS',
            VALUE    => 'NULL',
        );

        $queues->Limit(
            FIELD           => 'Lifecycle',
            VALUE           => '',
            ENTRYAGGREGATOR => 'OR',
        );

        $queues->Limit(
            FIELD           => 'Lifecycle',
            VALUE           => 0,
            ENTRYAGGREGATOR => 'OR',
        );

        while ( my $q = $queues->Next ) {
            $q->SetLifecycle('default');
        }
    },
    sub {
        use strict;
        my $groups = RT::Groups->new(RT->SystemUser);
        $groups->Limit( FIELD    => 'Domain',
                        OPERATOR => '=',
                        VALUE    => 'Personal',
                        CASESENSITIVE => 0,
                      );
        $groups->LimitToDeleted;
        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();
        }
    },
);
