'Execute the command. Since this is designed to fix any issues cause by running pre-CohortMembership code
with the database already migrated to post-CohortMembership state, we will use the pre-CohortMembership
table CourseUserGroup as the canonical source of truth. This way, changes made in the window are persisted.'

def handle(self, *args, **options):

    commit = options['commit']
    memberships_to_delete = 0
    memberships_to_add = 0
    for membership in CohortMembership.objects.all():
        try:
            CourseUserGroup.objects.get(group_type=CourseUserGroup.COHORT, users__id=membership.user.id, course_id=membership.course_id, id=membership.course_user_group.id)
        except CourseUserGroup.DoesNotExist:
            memberships_to_delete += 1
            if commit:
                membership.delete()
    for course_group in CourseUserGroup.objects.filter(group_type=CourseUserGroup.COHORT):
        for user in course_group.users.all():
            try:
                CohortMembership.objects.get(user=user, course_id=course_group.course_id, course_user_group_id=course_group.id)
            except CohortMembership.DoesNotExist:
                memberships_to_add += 1
                if commit:
                    membership = CohortMembership(course_user_group=course_group, user=user, course_id=course_group.course_id)
                    try:
                        membership.save()
                    except IntegrityError:
                        course_group.users.remove(user)
                        user.course_groups.remove(course_group)
    print '{}    CohortMemberships    did    not    match    the    CourseUserGroup    table    and    will    be    deleted'.format(memberships_to_delete)
    print '{}    CourseUserGroup    users    do    not    have    a    CohortMembership;    one    will    be    added    if    it    is    valid'.format(memberships_to_add)
    if commit:
        print 'Changes    have    been    made    and    saved.'
    else:
        print 'Dry    run,    changes    have    not    been    saved.    Run    again    with    "commit"    argument    to    save    changes'
