#!/usr/bin/env python3

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

# 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'
)


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 create_zoperepo(tmp):
    '''
    If we only have a Data.FS, we need to create a zope instance that accesses
    it and records the contents.

    1. Create a Zope config that accesses the Data.FS (read only?)
    2. Create zodbsync config that accesses it
    3. Run zodbsync record
    4. Initialize git
    '''

    path = config['datafs_path']
    os.makedirs(source_zoperepo, exist_ok=True)

    with open(f'{tmp}/zope.conf', 'w') as f:
        f.write(f'''\
instancehome {tmp}
<zodb_db main>
pool-size 25
<filestorage>
path {path}
</filestorage>
mount-point /
</zodb_db>
<zodb_db temporary>
<temporarystorage>
  name temporary storage for sessioning
</temporarystorage>
mount-point /temp_folder
container-class Products.TemporaryFolder.TemporaryContainer
</zodb_db>
        ''')

    with open(f'{tmp}/zodbsync.py', 'w') as f:
        f.write(f'''\
conf_path = '{tmp}/zope.conf'
manager_user = 'perfact'
default_owner = 'perfact'
base_dir = '{source_zoperepo}'
        ''')

    sp.run(['zodbsync', '-c', f'{tmp}/zodbsync.py', 'record', '/'],
           check=True)

    gitcmd = ['git', '-C', source_zoperepo]
    sp.run(gitcmd + ['init'], check=True)
    sp.run(gitcmd + ['add', '.'], check=True)
    sp.run(gitcmd + ['commit', '-m', 'Initial Commit'], check=True)


if __name__ == '__main__':
    with tempfile.TemporaryDirectory() as tempdir:
        create_zoperepo(tmp=tempdir)
