#!/usr/bin/env python3

import os
import pathlib
import io
import glob
import subprocess
import logging

logger = logging.getLogger(__name__)

logging.basicConfig(level=logging.INFO)

cache_path = pathlib.Path.cwd() / 'tmp'

project_root = pathlib.Path.cwd()

logger.info(dict(project_root=project_root, cache_path=cache_path,))

for service in [
    pathlib.Path(o) for o in sum([
        glob.glob('d1/*.service'),
        glob.glob('d1/*.timer')
    ], [])
]:
    os.makedirs(str((cache_path / service).parent), exist_ok=True)

    with io.open(str(service), 'r') as f:
        with io.open(
            str(cache_path / service), 'w'
        ) as f2:
            f2.write(
                f.read().replace(
                    '{{PROJECT_ROOT}}',
                    str(project_root),
                )
            )
    logger.info(dict(
        service=str(service),
        msg='updated',
    ))
