#!/usr/bin/env python3

from pprint import pprint
import pathlib
import csv
import os
import re
import glob
import argparse
from build_aux.build_common import *


G_RPM_VERSION = None
G_SRPM_PATH = None
G_MOCK_SRPM_ROOT = None
G_MOCK_RPM_ROOT = None
SPEC_FILE_PATH = None
G_LOCAL_RPM_DIR = "tmp"
G_SOURCES_DIR = f"{G_LOCAL_RPM_DIR}/SOURCES"
G_SPECS_DIR = f"{G_LOCAL_RPM_DIR}/SPECS"
COPR_REPO = "sysd-manager"

parser = argparse.ArgumentParser(description="Copr RPM builder",
                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument("action", 
                    help="ction to perform", default="mock", choices=["mock", "spec", "srpm", "copr", "clean"])

parser.add_argument("-d", "--allow_dirty", action="store_true", dest="allow_dirty",
                    help="allow not commited file", default=False)

parser.add_argument("-a", "--arch",  dest="architecture",
                    help="build architecture", default="x86_64")


parser.add_argument("-o", "--only",  dest="only", action="store_true",
                    help="only use build mode", default=False)

args = parser.parse_args()

ARCH = args.architecture
print(f"{color.BOLD}Build for {color.CYAN}Copr{
      color.END} architecture {color.CYAN}{ARCH}{color.END}")


def main():
    match args.action:
        case "spec":
            init()
            build_spec()
        case "srpm":
            init()
            if not args.only:
                build_spec()
            buildSRPM()
        case "mock":
            init()
            if not args.only:
                build_spec()
                buildSRPM()
            mock()
        case "copr":
            init()
            if not args.only:
                build_spec()
                buildSRPM()
            copr()
        case "clean":
            clean()


def build_spec():
    print(f"{color.CYAN}{color.BOLD}Info:{color.END} make source")

    cmd_run(["git", "archive",
                    "--format=tar",
                    f"--prefix=sysd-manager-{G_RPM_VERSION}/",
                    f"--output={G_SOURCES_DIR}/sysd-manager-{G_RPM_VERSION}.crate",
                    "HEAD"])
    
    print(f"{color.CYAN}{color.BOLD}Info:{color.END} make specfile")

    global SPEC_FILE_PATH
    SPEC_FILE_PATH = f"{G_SPECS_DIR}/rust-sysd-manager.spec"

    print(f"{color.CYAN}{color.BOLD}Info:{color.END} replace FIXME licence")

    file_path = "rust-sysd-manager.spec"
    case_insensitive_search_and_replace(
        file_path, SPEC_FILE_PATH, r"Version:.*", f"Version:        {G_RPM_VERSION}")


def case_insensitive_search_and_replace(file_path, file_path_out, search_word, replace_word):
    with open(file_path, 'r') as file:

        pattern = re.compile(search_word)
        file_contents = file.read()
        updated_contents = pattern.sub(replace_word, file_contents)

    with open(file_path_out, 'w') as file:
        print(f"{color.CYAN}{color.BOLD}Info:{color.END} write transfoermed file from '{file_path}' to '{file_path_out}'")
        file.write(updated_contents)


def init():
    if is_repo_dirty():
        print("git repo dirty")
        if args.allow_dirty:
            print("Bypass dity")
        else:
            exit()

    global VERSION_ID
    global G_MOCK_SRPM_ROOT
    global G_MOCK_RPM_ROOT
    global G_RPM_VERSION

    cargo_toml = toml() 

    G_RPM_VERSION = cargo_toml['package']['version']

    path = pathlib.Path("/etc/os-release")
    with open(path) as stream:
        reader = csv.reader(stream, delimiter="=")
        os_release = dict(reader)

    VERSION_ID = os_release['VERSION_ID']
    #VERSION_ID="rawhide"
    # use host's arch for srpm
    G_MOCK_SRPM_ROOT = f"fedora-{VERSION_ID}-{ARCH}"
    # use user's arch for rpm
    G_MOCK_RPM_ROOT = f"fedora-{VERSION_ID}-{ARCH}"

    clean()
    cmd_run(["mkdir", "-p", f"{G_LOCAL_RPM_DIR}/SPECS"])
    cmd_run(["mkdir", "-p", G_SOURCES_DIR])

    os.environ["RPM_VERSION"] = G_RPM_VERSION
    print("cargo version", G_RPM_VERSION)

def clean():
    cmd_run(["rm", "-rf", G_LOCAL_RPM_DIR])
    clean_gschema()

def buildSRPM():
    print(f"{color.CYAN}{color.BOLD}Info:{color.END} build SRPM")

    cmd_run(["tree", G_LOCAL_RPM_DIR])

    cmd_run(["mock", "--buildsrpm",
                    "--root", G_MOCK_SRPM_ROOT,
                    "--spec", SPEC_FILE_PATH,
                    "--sources", G_SOURCES_DIR])

    print(f"{color.CYAN}{color.BOLD}Info:{
          color.END} copy SRPM to '{G_LOCAL_RPM_DIR}'")
    cmd_run(["ls", "-l", f"/var/lib/mock/{G_MOCK_SRPM_ROOT}/result"])

    cmd_run(
        [f"cp -v /var/lib/mock/{G_MOCK_SRPM_ROOT}/result/rust-sysd-manager-*.src.rpm {G_LOCAL_RPM_DIR}"], shell=True)

    set_srpm_path()


def set_srpm_path():
    global G_SRPM_PATH
    path = f"tmp/rust-sysd-manager-{G_RPM_VERSION}-*.src.rpm"
    for filename in glob.glob(path):
        G_SRPM_PATH = filename

    print(f"{color.CYAN}{color.BOLD}SRPM path:{color.END} {G_SRPM_PATH}")


def mock():
    print(f"{color.BOLD}{color.CYAN}Info:${color.END} Build localy RPM (mock) for ${
          color.BOLD} {ARCH}{color.END}")

    cmd_run(["mock", "--rebuild",
                    "--root", G_MOCK_SRPM_ROOT,
                    "--spec", SPEC_FILE_PATH,
                    G_SRPM_PATH])

    location = f"/var/lib/mock/{G_MOCK_RPM_ROOT}/result"
    print(f"{color.BOLD}{color.CYAN}Info:{
          color.END} Build result on '{location}'")
    cmd_run(["ls", "-l", location])

    cmd_run(
        [f"cp -v /var/lib/mock/{G_MOCK_RPM_ROOT}/result/sysd-manager-{G_RPM_VERSION}*{ARCH}.rpm {G_LOCAL_RPM_DIR}"], shell=True)


def copr():
    print(f"{color.BOLD}{color.CYAN}Info:{color.END} copr build {color.BOLD}{COPR_REPO}{
          color.END} of {color.BOLD}{G_SRPM_PATH}{color.END} for {color.BOLD}{ARCH}{color.END}")

    cmd_run(["copr-cli", "build", "-r",
                   G_MOCK_RPM_ROOT, COPR_REPO, G_SRPM_PATH])


main()