#!/usr/bin/env python3

import subprocess as sp
import importlib.machinery
import importlib.util

# Calculate the module path from the current path
config_path = '/opt/perfact/migration/config/migration_conf.py'
source_zoperepo = (
    '/opt/perfact/custom/migration/source_system/opt/perfact/dbutils-zoperepo'
)
target_zoperepo = ('/opt/perfact/dbutils-zoperepo')


def load_config(filename, name='config'):
    '''
    Load a configuration file and return it as dictionary, skipping any fields
    starting with _.
    '''
    loader = importlib.machinery.SourceFileLoader(name, filename)
    spec = importlib.util.spec_from_loader(loader.name, loader)
    mod = importlib.util.module_from_spec(spec)
    loader.exec_module(mod)
    return {
        name: getattr(mod, name)
        for name in dir(mod)
        if not name.startswith('_')
    }


# load configuration
config = load_config(config_path)


def playback(paths):
    '''Call zodbsync playback on the given subpath under __root__'''
    sp.run(
        ['zodbsync', 'playback', '--override', '--skip-errors'] + paths,
        check=True
    )


def migrate_folders():
    '''Use specified mappings to move files from source repo to target
    and playback the changes directly, after that rollback changes to source
    repo
    '''
    foldermappings = config.get('zoperepo_folder_mappings', None)
    if not foldermappings:
        print('No Mappings defined, nothing will be moved')
        return

    for source, target in foldermappings.items():
        source_path = f'{source_zoperepo}/__root__/{source}'
        target_path = f'{target_zoperepo}/__root__/{target}'
        # First cleanup target folder, otherwise move might think we want
        # to move to a subfolder
        sp.run(
            ['rm', '-Rf', target_path],
            check=True
        )
        sp.run(
            ['mv', source_path, target_path],
            check=True
        )
    playback(list(foldermappings.values()))
    sp.run(
        ['git', '-C', source_zoperepo, 'reset', '--hard', 'HEAD'],
        check=True
    )


if __name__ == '__main__':
    migrate_folders()
