#!/usr/bin/env python3
## Maintainer : @T-Dynamos
import os
import json
import sys

filename = os.path.basename(sys.argv[0])

usage = f"""
Usage:

{filename} <package> ...            

Add or increment TERMUX_PKG_REVISION of package. 


{filename} --dependencies  <package>    

Add or increment TERMUX_PKG_REVISION of all the packages that have <package> in TERMUX_PKG_DEPENDS or in TERMUX_PKG_BUILD_DEPENDS
"""

REPO_PATH = os.path.join("/".join(os.path.realpath(sys.argv[0]).split("/")[:-3]), "repo.json")
FOLDERS = []
for folder in list(json.load(open(REPO_PATH)).keys()):
    if folder != "pkg_format":
        FOLDERS.append(folder)


def is_dep(DEP: str, line: str) -> bool:
    """
    Checks if the dep is in line
    """
    tmp_deps = line.split("=")[1]
    if tmp_deps.startswith('"'):
        deps = [dep.strip() for dep in tmp_deps.split('"')[1].split(",")]
    elif tmp_deps.startswith("'"):
        deps = [dep.strip() for dep in tmp_deps.split("'")[1].split(",")]
    else:
        deps = [tmp_deps]

    return DEP in deps


def get_build_dependent_files(folders: list, DEP: str) -> list:
    """
    Gets all the packages that depend on some package
    """
    build_files = set()
    for d in folders:
        for folder in os.listdir(d):
            if os.path.exists(os.path.join(d, folder, "build.sh")):
                with open(os.path.join(d, folder, "build.sh"), "r") as file:
                    for line in file.read().split("\n"):
                        if line.startswith("TERMUX_PKG_DEPENDS") or line.startswith(
                            "TERMUX_PKG_BUILD_DEPENDS"
                        ):
                            if is_dep(DEP, line):
                                build_files.add(os.path.join(d, folder, "build.sh"))
                for subfile_name in os.listdir(os.path.join(d, folder)):
                    if subfile_name.endswith(".subpackage.sh"):
                        with open(os.path.join(d, folder, subfile_name)) as file:
                            for line in file.read().split("\n"):
                                if line.startswith("TERMUX_SUBPKG_DEPENDS"):
                                    if is_dep(DEP, line):
                                        build_files.add(os.path.join(d, folder, "build.sh"))
    return build_files


def bump_revision(file: str) -> None:
    """
    Bumps version in file
    """
    opened_file = open(file, "r")
    file_read = opened_file.read().split("\n")
    revision = 0

    if "TERMUX_PKG_REVISION" in "\n".join(file_read):
        for line in file_read:
            if line.startswith("TERMUX_PKG_REVISION"):
                revision = line.split("=")[-1]
                if revision.startswith('"'):
                    revision = revision.split('"')[1]
                revision = int(revision) + 1
                file_read[file_read.index(line)] = (
                    line.split("=")[0] + "=" + str(revision)
                    )
                break

    else:
        for line in file_read:
            if line.startswith("TERMUX_PKG_VERSION"):
                file_read.insert(file_read.index(line) + 1, "TERMUX_PKG_REVISION=1")
                revision = 1
                break

    opened_file.close()
    opened_file = open(file,"w")
    opened_file.write("\n".join(file_read))
    opened_file.close()
    print("{} -> {} {}".format(revision - 1, revision, file))


def locate_dir(file: str) -> str:
    """
    Finds package in repo
    """
    for repo in FOLDERS:
        if file in os.listdir(repo):
            file_final = f"{repo}/{file}/build.sh"
            return file_final if os.path.exists(file_final) else exit("Error : File {} does not exists!".format(file_final))
    return exit("Package {} not found".format(file))


def parse_args() -> None:
    if len(sys.argv) == 1 or sys.argv[1] in ["--help", "-h"]:
        print(usage)
        exit(0)

    if sys.argv[1] in ["--dependencies", "-d"] and len(sys.argv) > 2:
        build_files = get_build_dependent_files(FOLDERS, os.path.basename(sys.argv[2]))
        print("Bumping all {} files".format(len(build_files)), end="\n\n")
        for files in build_files:
            bump_revision(files)
        exit(0)

    if len(sys.argv) >= 2 and sys.argv[1] not in ["--dependencies", "-d"]:
        print("Bumping {} packages".format(len(sys.argv[1:])), end="\n\n")
        packages = sys.argv[1:]
        for package in packages:
            bump_revision(locate_dir((
                    os.path.basename(package[:-1]) if package[-1] == "/" else os.path.basename(package)
                    ) if "/" in package else package))
        exit(0)

    else:
        print(usage)
        exit(0)


if __name__ == "__main__":
    parse_args()
