#!/usr/bin/env python3

import os
import subprocess
import importlib.machinery

# Calculate the module path from the current path
base_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
config_path = os.path.join(base_path, 'config')
build_path = os.path.join(base_path, 'build')

# load configuration
config = importlib.machinery.SourceFileLoader(
    'config',
    os.path.join(config_path, 'source_conf.py')
).load_module()

# transform into dict
config = {
    key: getattr(config, key)
    for key in dir(config)
    if not key.startswith('__')
}

repo = os.path.join(build_path, 'sourcerepo')
remote = '{source_system}:/opt/perfact/dbutils-zoperepo'.format(**config)

if not os.path.isdir(repo):
    print("Repository not found, cloning")
    subprocess.run(
        ['git', 'clone', remote, repo, ],
        check=True,
    )

# To be sure, set origin url
subprocess.run(
    ['git', '-C', repo, 'remote', 'set-url', 'origin', remote],
    check=True,
)

print('Fetching and resetting.')
subprocess.run(
    ['git', '-C', repo, 'fetch', 'origin'],
    check=True,
)

subprocess.run(
    ['git', '-C', repo, 'reset', '--hard',
     'origin/{source_branch}'.format(**config)],
    check=True,
)
