#!/usr/local/bin/python3.14
# SPDX-License-Identifier: AGPL-3.0-or-later
import logging
import sys

import kopano

"""
synchronize permissions to archive stores

"""

ROLE_REVIEWER = ['folder_visible', 'read_items']

def logger(options):
    logging.basicConfig(stream=sys.stdout, level=options.loglevel)
    return logging.getLogger('aclset')

def main():
    parser = kopano.parser('spkul')
    options, args = parser.parse_args()
    log = logger(options)
    stats = {'users': 0, 'errors': 0}
    server = kopano.server(options=options)

    for user in server.users():
        with kopano.log_exc(log, stats):
            log.info('processing user %s', user.name)
            stats['users'] += 1

            archive_store, archive_folder = user.archive_store, user.archive_folder

            if archive_store:
                log.debug('syncing permissions')

                # for the user store, copy rights (masked to ROLE_REVIEWER)
                for p in user.store.permissions():
                    rights = [r for r in p.rights if r in ROLE_REVIEWER]
                    log.debug('setting rights: %s on the store for user: %s', rights, p.member.name)
                    archive_folder.permission(p.member, create=True).rights = rights
                archive_folder.permission(kopano.Group('Everyone'), create=True).rights = []

                # if archiving to subfolder, copy store rights to subtree, adding 'folder_visible'
                if archive_folder is not archive_store.subtree:
                    log.debug('setting rights to subtree from store rights')
                    for p in user.store.permissions():
                        pa = archive_store.subtree.permission(p.member, create=True)
                        pa.rights = [r for r in pa.rights if r != 'folder_visible'] + ['folder_visible']

                # for each folder, copy rights (masked to ROLE_REVIEWER)
                for folder in user.folders():
                    archive_folder = folder.archive_folder
                    if archive_folder:
                        for p in folder.permissions():
                            rights = [r for r in p.rights if r in ROLE_REVIEWER]
                            log.debug('setting rights: %s to folder: %s for user: %s', rights, folder.name, p.member.name)
                            archive_folder.permission(p.member, create=True).rights = rights

            else:
                log.debug('user has no archive store')

if __name__ == '__main__':
    main()
