#!/usr/bin/env python3
# Copyright 2023 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import shutil
import argparse
import subprocess

from datetime import datetime

current_dir = os.path.dirname(os.path.abspath(__file__))
package = os.path.join("testflows", "github", "hetzner", "runners")
init_path = os.path.join(current_dir, package, "__init__.py")
setup_path = os.path.join(current_dir, "setup.py")

parser = argparse.ArgumentParser(
    description="TestFlows - GitHub Actions Runners using Hetzner Cloud packaging script"
)
parser.add_argument(
    "--debug", help="enable debugging", action="store_true", default=False
)


def get_base_version():
    """Return package base version."""
    version = None
    with open(os.path.join(current_dir, package, "__init__.py")) as fd:
        for line in fd.readlines():
            if line.startswith("__version__ = "):
                match = re.match('__version__\s=\s"(?P<version>.+).__VERSION__', line)
                if match:
                    version = match.groupdict().get("version")
                    if version:
                        break
    if not version:
        raise ValueError("failed to get base version number")
    return version


def get_revision():
    """Return build revision."""
    now = datetime.utcnow()
    major_revision = now.strftime("%y%m%d")
    minor_revision = now.strftime("%H%M%S")
    return major_revision + ".1" + minor_revision


def set_version(path, version):
    """Set version in the file.

    :param path: path
    :param version: version
    """
    with open(path, "a+") as fd:
        fd.seek(0)
        content = fd.read()
        fd.seek(0)
        fd.truncate()
        fd.write(content.replace("__VERSION__", version))
    return content


def unset_version(path, content):
    """Unset version in the file.

    :param path: path
    :param content: original file content
    """
    with open(path, "a+") as fd:
        fd.seek(0)
        fd.truncate()
        fd.write(content)


def build_package(args, options):
    """Build package.

    :param args: arguments
    :param options: extra options
    """
    subprocess.run(
        ["/usr/bin/env", "python3", "setup.py"]
        + (["-q"] if not args.debug else [])
        + ["sdist"]
        + (options if options else [])
    )


def build(args, options=None):
    """Build package.

    :param args: arguments
    :param options: build options, default: ``None``
    """
    if options is None:
        options = []

    if os.path.exists("dist"):
        shutil.rmtree("dist")

    base_version = get_base_version()
    revision = get_revision()
    version = ".".join([base_version, revision])
    init_content, setup_content = None, None

    try:
        init_content = set_version(init_path, revision)
        setup_content = set_version(setup_path, version)
        build_package(args, options)
    finally:
        if init_content:
            unset_version(init_path, init_content)
        if setup_content:
            unset_version(setup_path, setup_content)


if __name__ == "__main__":
    args = parser.parse_args()
    build(args)
