<reponame>hmrc/devops-tooling-build
import errno
import os

import hcl
import tempfile
import yaml

from pathlib import Path

import constant
import common

from . import common as tf_common


def get_tf_path(environment: str, component: Path) -> Path:
    base = common.resolve_symlink(Path('/mnt/repo'))
    return base / component / environment


def get_tf_version(environment: str, component: Path) -> str:
    tf_path = get_tf_path(environment, component)
    return tf_common.get_tf_version(tf_path)


def tf_configure_backend(workdir: Path, tf_path: Path) -> None:
    environment = tf_path.name
    backend_name = tf_path.parent.name
    if tf_path.is_dir():
        backend_path = tf_path/'backend.tf'
    else:
        backend_path = tf_path.parent/'backend.tf'
    with backend_path.open('r') as fp:
        try:
            backend_hcl = hcl.load(fp)
        except hcl.Error as exc:
            rel_path = backend_path.relative_to(os.environ['REPO_MNT'])
            print(f"HCL error in {rel_path}:")
            print(exc)
            raise
    with open(constant.PATH_APP_DATA, 'r') as fp_data:
        tf_bucket_suffix = yaml.safe_load(fp_data)['tf-bucket-suffix']
    backend_hcl['terraform']['backend']['s3'].update({
        'bucket':           f"terraform-{environment}-{tf_bucket_suffix}",
        'dynamodb_table':   f"terraform-{environment}-tflock",
        'key':              f"{backend_name}.tfstate",
    })
    with (workdir/'backend.tf.json').open('w') as fp:
        fp.write(hcl.dumps(backend_hcl))


def prepare(environment: str, component: Path) -> Path:

    if not component.exists():
        print(f"{component} Not found. Did you mount the correct directory?")
        raise FileNotFoundError(errno.ENOENT,
                                os.strerror(errno.ENOENT),
                                component)

    base = common.resolve_symlink(Path('/mnt/repo'))
    tf_path = base/component/environment
    env_path = base/'environment_variables'

    if component.name == 'tfstate-buckets':
        workdir = tf_path
    else:
        workdir = Path(tempfile.mkdtemp())
        tf_configure_backend(workdir, tf_path)

        ignored_files = ['backend.tf', r'.*\.tfplan', r'.*\.vars']
        tf_common.tf_configure_environment(
            workdir, tf_path, ignored_files, env_path,
        )

    return workdir

import errno
import os

import hcl
import tempfile
import yaml

from pathlib import Path

import constant
import common

from . import common as tf_common


def get_tf_path(environment: str, component: Path) -> Path:
    base = common.resolve_symlink(Path('/mnt/repo'))
    return base / component / environment


def get_tf_version(environment: str, component: Path) -> str:
    tf_path = get_tf_path(environment, component)
    return tf_common.get_tf_version(tf_path)


def tf_configure_backend(workdir: Path, tf_path: Path) -> None:
    environment = tf_path.name
    backend_name = tf_path.parent.name
    if tf_path.is_dir():
        backend_path = tf_path/'backend.tf'
    else:
        backend_path = tf_path.parent/'backend.tf'
    with backend_path.open('r') as fp:
        try:
            backend_hcl = hcl.load(fp)
        except hcl.Error as exc:
            rel_path = backend_path.relative_to(os.environ['REPO_MNT'])
            print(f"HCL error in {rel_path}:")
            print(exc)
            raise
    with open(constant.PATH_APP_DATA, 'r') as fp_data:
        tf_bucket_suffix = yaml.safe_load(fp_data)['tf-bucket-suffix']
    backend_hcl['terraform']['backend']['s3'].update({
        'bucket':           f"terraform-{environment}-{tf_bucket_suffix}",
        'dynamodb_table':   f"terraform-{environment}-tflock",
        'key':              f"{backend_name}.tfstate",
    })
    with (workdir/'backend.tf.json').open('w') as fp:
        fp.write(hcl.dumps(backend_hcl))


def prepare(environment: str, component: Path) -> Path:

    if not component.exists():
        print(f"{component} Not found. Did you mount the correct directory?")
        raise FileNotFoundError(errno.ENOENT,
                                os.strerror(errno.ENOENT),
                                component)

    base = common.resolve_symlink(Path('/mnt/repo'))
    tf_path = base/component/environment
    env_path = base/'environment_variables'

    if component.name == 'tfstate-buckets':
        workdir = tf_path
    else:
        workdir = Path(tempfile.mkdtemp())
        tf_configure_backend(workdir, tf_path)

        ignored_files = ['backend.tf', r'.*\.tfplan', r'.*\.vars']
        tf_common.tf_configure_environment(
            workdir, tf_path, ignored_files, env_path,
        )

    return workdir