import os, sys, time, re
from colorama import *

def create_directory(path):
    if not os.path.exists(path):
        os.makedirs(path)

def create_file(path, content):
    if not os.path.exists(path):
        with open(path, "w") as file:
            file.write(content)

directories = ["bin", "info", "log", "uninstall"]
for directory in directories:
    create_directory(directory)

rni_info_content = """Name: rni
Version: 0.0.7
Summary: rni
Home-page: https://rasmnout.github.io/rni
Github Repository: https://github.com/rasmnout/rni
Author: trspn ( Rasmnout Owner )
Author-email: rasmnout@gmail.com
License: Apache
Description: Rni is used to install the package from github and other sites
Requires: python3
Changelog: "1.0.0: Fixed Problems."
Rni: rasmnout/rni
Dist: "rni-v007.py"
"""

create_file("rni-info", rni_info_content)
create_file("uninstall-info", "")
home_directory = os.path.expanduser("~")
with open(os.path.join(home_directory, ".bashrc"), "r") as f:
        trying = f.read()
        if 'export PATH="/rni/bin:/usr/local/bin:/bin:$PATH"' not in trying:
                with open(os.path.join(home_directory, ".bashrc"), "a") as f:
                        f.write('export PATH="/rni/bin:/usr/local/bin:/bin:$PATH"')
with open(f"/root/.bashrc","r") as f:
        trying = f.read()
        if 'export PATH="/rni/bin:/usr/local/bin:/bin:$PATH"' not in trying:
                with open(f"/root/.bashrc","a") as f:
                        f.write('export PATH="/rni/bin:/usr/local/bin:/bin:$PATH"')
need_delete = None
def get_time():
        return time.strftime("%H:%M:%S")
def remove(destro=""):
        print(f"{get_time()} {Fore.CYAN}INFO{Fore.RESET}: Getting Information about uninstall:")
        with open("/rni/log/uninstall-info","r") as f:
                print(f"{get_time()}    - reading uninstall info.")
                print(f"{get_time()}    - done, reading.")
                for line in f:
                        new_line = line.strip()
                        if destro in new_line:
                                need_delete = new_line
                                name, name_destro = new_line.split(" - ")
                                print(f"{get_time()} {Fore.CYAN}INFO{Fore.RESET}: Deleting Files.")
                                with open(f"/rni/uninstall/{name}","r") as f2:
                                        for line2 in f2:
                                                new_line2 = line2.strip()
                                                file_path = f"/rni/bin/{new_line2}"
                                                print(f"{get_time()} Deleting {new_line2}")
                                                try:
                                                        os.remove(file_path)
                                                        print(f"{get_time()}    - Deleted {new_line2}")
                                                except Exception as e:
                                                        print(f"{get_time()} ERROR: {new_line2} {e}")
                        else:
                                print(f"{get_time()} Package {destro} was not found.")
                                sys.exit()
                print(f"{get_time()} {Fore.CYAN}INFO{Fore.RESET}: All packages are deleted.")
                print(f"{get_time()} {Fore.CYAN}INFO{Fore.RESET}: Deleting uninstall information:")
                try:
                        print(f"{get_time()} Deleting uninstall dist:")
                        os.remove(f"/rni/uninstall/{name}")
                        print(f"{get_time()}    - Deleted uninstall-{name}")
                except Exception as e:
                        print(f"{get_time()} ERROR: {e}")
                try:
                        print(f"{get_time()} Deleting local information:")
                        os.remove(f"/rni/info/{name}")
                        print(f"{get_time()}    - Deleted info-{name}")
                except Exception as e:
                        print(f"{get_time()} ERROR: {e}")
                print(f"{get_time()} Changing the uninstall database")
                with open("/rni/log/uninstall-info","r") as f:
                        whole_output = f.read()
                        change_whole_output = whole_output.replace(need_delete,"")
                with open("/rni/log/uninstall-info","w") as f:
                        f.write(change_whole_output)
                print(f"{get_time()} {Fore.CYAN}INFO{Fore.RESET}: Package was remove!")
path = "/rni/info/"
def list():
        if os.path.exists(path) and os.path.isdir(path):
                for file in os.listdir(path):
                        with open(f"{path}{file}", "r") as f:
                                output = f.read()
                                pattern = r"(Version):\s*(.*?)\n"
                                matches = re.findall(pattern, output)
                                version = None
                                for key, val in matches:
                                        if key == "Version":
                                                version = val
                                print(f"{Fore.CYAN}{Style.BRIGHT}{file}{Style.RESET_ALL} - v{Fore.GREEN}{version}{Fore.RESET}")
import requests, re, time, os, sys
from colorama import init, Fore, Style

# Inicializace colorama
init(autoreset=True)

# Barevné konstanty
INFO_COLOR = f"{Style.BRIGHT}{Fore.CYAN}"
PROGRESS_COLOR = f"{Style.BRIGHT}{Fore.MAGENTA}"
IMPORTANT_COLOR = f"{Style.BRIGHT}{Fore.YELLOW}"
RESET = Style.RESET_ALL

def get_time():
    return time.strftime("%H:%M:%S")

def install(destro="", out=False):
    version_problem = False
    print(f"{get_time()} {INFO_COLOR}INFO{Fore.RESET}: Getting Information about {destro}:{RESET}")

    # Sestavení URL podle parametru out
    if not out:
        com_url = f"https://raw.githubusercontent.com/{destro}/main/rni/"
        repo_url = f"https://raw.githubusercontent.com/{destro}/main/rni/rni-repo"
    else:
        com_url = f"{destro}rni/"
        repo_url = f"{destro}rni/rni-repo"

    # Stažení repozitáře s informacemi
    response = requests.get(repo_url)
    print(f"{get_time()}    - Received response from server.")
    if response.status_code == 200:
        output = response.text
        output_to_info = output
        pattern = r"(Rni|Dist|Name):\s*(.*?)\n"
        print(f"{get_time()}    - Searching for installation file info.")
        matches = re.findall(pattern, output)
        # Inicializace proměnných
        rni, dist, name = None, None, None
        for key, value in matches:
            if key == "Rni":
                rni = value
            elif key == "Dist":
                dist = value
            elif key == "Name":
                name = value
    else:
        print(f"{get_time()} {IMPORTANT_COLOR}ERROR: Failed to get repository info.{RESET}")
        return

    print(f"{get_time()} {INFO_COLOR}INFO{Fore.RESET}: Installing {name}{RESET}")

    # Vytvoření relativních cest k adresářům, kde se budou soubory instalovat
    base_dir = os.path.abspath(os.path.dirname(__file__))
    bin_dir = "/rni/bin"
    info_dir = "/rni/info"
    uninstall_dir = "/rni/uninstall"
    log_dir = "/rni/log"

    # Ujistíme se, že adresáře existují
    for directory in [bin_dir, info_dir, uninstall_dir, log_dir]:
        os.makedirs(directory, exist_ok=True)

    # Rozdělení seznamu programů; odstraníme případné přebytečné uvozovky
    items = dist.split('","')
    items[0] = items[0].strip('"')
    items[-1] = items[-1].strip('"')
    print(f"{get_time()} {INFO_COLOR}INFO{Fore.RESET}: Programs to be installed: {items}{RESET}")

    all_items = ""
    total_items = len(items)

    for idx, item in enumerate(items):
        percent = int((idx + 1) / total_items * 100)
        print(f"{get_time()} {PROGRESS_COLOR}Progress: {percent}%{RESET}")

        local_path = os.path.join(bin_dir, item)
        server_item_url = f"{com_url}dist/{item}"

        if os.path.exists(local_path):
            print(f"{get_time()}    - {Style.BRIGHT}{item} was found{RESET}")
            print(f"{get_time()}    - Verifying {Style.BRIGHT}{item}{RESET}")

            response_verify = requests.get(server_item_url)
            if response_verify.status_code == 200:
                output_verify = response_verify.text
            else:
                print(f"{get_time()} {IMPORTANT_COLOR}ERROR: Failed to fetch {item} from server.{RESET}")
                continue

            with open(local_path, "r") as f:
                local_content = f.read()

            if local_content == output_verify:
                print(f"{get_time()}    - {item} is up-to-date.")
                all_items += f"{item}\n"
                continue  # Přeskočíme instalaci/updat, pokud je vše aktuální
            else:
                # Získání verze z repozitáře
                response_repo = requests.get(repo_url)
                if response_repo.status_code == 200:
                    output_repo = response_repo.text
                    pattern_version = r"(Version):\s*(.*?)\n"
                    matches_version = re.findall(pattern_version, output_repo)
                    version = None
                    for key, val in matches_version:
                        if key == "Version":
                            version = val
                else:
                    print(f"{get_time()} {IMPORTANT_COLOR}ERROR: Failed to fetch version info from repository.{RESET}")
                    version = None

                print(f"{get_time()}    - {Style.BRIGHT}{item}{RESET} needs to be updated.")

                # Čtení lokální verze ze souboru v info adresáři
                safe_name = name.replace("/", "").replace('"', "").replace("'", "")
                local_info_path = os.path.join(info_dir, safe_name)
                if os.path.exists(local_info_path):
                    with open(local_info_path, "r") as f:
                        local_info_content = f.read()
                    pattern_version = r"(Version):\s*(.*?)\n"
                    matches_version_local = re.findall(pattern_version, local_info_content)
                    version_local = None
                    for key, val in matches_version_local:
                        if key == "Version":
                            version_local = val
                else:
                    version_local = None

                if version == version_local:
                    choice = input(f"{get_time()}    - {Style.BRIGHT}{item}{RESET} is different from the server but has the same version.\nDo you want to update {item}? (Y/n): ")
                    if choice.lower() == "y":
                        with open(local_path, "w") as f:
                            f.write(output_verify)
                        print(f"{get_time()}    - {Style.BRIGHT}{item}{RESET} updated.")
                    else:
                        print(f"{get_time()}    - {Style.BRIGHT}{item}{RESET} update aborted.")
                        choice2 = input(f"{get_time()}    - Do you want to abort all packages? (Y/n): ")
                        if choice2.lower() == "y":
                            sys.exit()
                else:
                    with open(local_path, "w") as f:
                        f.write(output_verify)
                    print(f"{get_time()}    - {Style.BRIGHT}{item}{RESET} updated.")
        else:
            print(f"{get_time()} {INFO_COLOR}INFO{Fore.RESET}: Installing {item}:{RESET}")
            print(f"{get_time()}    - Searching for {Style.BRIGHT}{item}{RESET}")
            response_item = requests.get(server_item_url)
            if response_item.status_code == 200:
                output_item = response_item.text
                with open(local_path, "w") as f:
                    f.write(output_item)
                print(f"{get_time()}    - {Style.BRIGHT}{item}{RESET} installed!")
                command_chmod = f"chmod +x {item}"
                os.system(command_chmod)
            else:
                print(f"{get_time()} {IMPORTANT_COLOR}ERROR: Failed to fetch {item} from server.{RESET}")

        all_items += f"{item}\n"

    print(f"{get_time()} {INFO_COLOR}INFO{Fore.RESET}: Creating information about {name}{RESET}")
    safe_name = name.replace("/", "").replace('"', "").replace("'", "")
    info_path = os.path.join(info_dir, safe_name)
    with open(f"/rni/info/{safe_name}", "w") as f:
        f.write(output_to_info)
    with open("/rni/log/uninstall-info", "a") as f:
        all = f"{safe_name} - {destro}"
        with open(f"/rni/log/uninstall-info","r") as f2:
            output = f2.read()
        if all in output:
            pass
        else:
            f.write(f"{safe_name} - {destro}\n")
    with open(f"/rni/uninstall/{safe_name}", "w") as f:
        f.write(all_items)
def search(destro="", out=False):
    if out == False:
        all_url = f"https://raw.githubusercontent.com/{destro}/main/rni/rni-repo"
    elif out == True:
        all_url = f"{destro}rni/rni-repo"  # Přidej 'http://' před destro
    response = requests.get(all_url)
    if response.status_code == 200:
        output = response.text
        pattern = r"(Name|Version|Summary|Home-page|Github Repository|Author|Author-email|License|Description|Requires|Changelog):\s*(.*?)\n"
        matches = re.findall(pattern, output)
        for match in matches:
            print(f'{match[0]}: {match[1]}')
    else:
        print(f"ERROR: {response.status_code}")


import os, sys, requests, time, re
from colorama import *

def get_time():
    return time.strftime("%H:%M:%S")
def current_version():
	with open("/rni/log/rni-info","r") as f:
		output = f.read()
	pattern = r"(Version):\s*(.*?)\n"
	matches = re.findall(pattern, output)
	for key, value in matches:
		if key == "Version":
			return value
def update():
    print(f"{get_time()} {Fore.CYAN}INFO{Fore.RESET}: Current Version RNI {current_version()}")
    repo_rni = "https://raw.githubusercontent.com/rasmnout/rni/main/rni/rni-repo"
    response = requests.get(repo_rni)

    if response.status_code == 200:
        output = response.text
        pattern = r"(Version|Dist):\s*(.*?)\n"
        matches = re.findall(pattern, output)
        version = None
        my_dist = None
        for key, value in matches:
            if key == "Version":
                version = value
            elif key == "Dist":
                my_dist = value
                my_final_dist = my_dist.replace('"','')

    with open("/rni/log/rni-info", "r") as f:
        output2 = f.read()
        pattern = r"(Version):\s*(.*?)\n"
        old_version = None
        matches = re.findall(pattern, output2)  # Opraveno: Použití output2 místo output

        for key, value in matches:
            if key == "Version":
                old_version = value

    if version == old_version:
        print(f"{get_time()} RNI v{version} is up-to-date")
    else:
        install(destro="rasmnout/rni", out=False)
        with open("/rni/log/rni-info", "w") as f:
            f.write(output)
        command_update = f"sudo python3 /rni/bin/{my_final_dist}"
        os.system(command_update)

os.system('export PATH="/rni/bin:/usr/local/bin:/bin:$PATH"')
import argparse
def my_main():
	parser = argparse.ArgumentParser(prog='rni.py', description='Package manager for multiple users.')
	subparsers = parser.add_subparsers(dest='command', required=True, help='Available commands')
	install_parser = subparsers.add_parser('install', help='Install a package from a specified source')
	install_parser.add_argument('url', nargs='?', help='Package source URL (e.g., https://rni.rasmnout.org/)')
	install_parser.add_argument('-git', metavar='repo', help='Install a package from GitHub (e.g., rasmnout/rni)')
	subparsers.add_parser('update', help='Update RNI for all users')
	remove_parser = subparsers.add_parser('remove', help='Uninstall a package')
	remove_parser.add_argument('package_name', help='Name of the package to remove')
	search_parser = subparsers.add_parser('search', help='Get package information from a source')
	search_parser.add_argument('url', nargs='?', help='Package source URL (e.g., https://rni.rasmnout.org/)')
	search_parser.add_argument('-git', metavar='repo', help='Get package info from GitHub (e.g., rasmnout/rni)')
	subparsers.add_parser('list', help='List all installed packages for all users')
	args = parser.parse_args()
	if args.command == "install":
		if args.git:
			install(destro=args.git, out=False)
		elif args.url:
			install(destro=args.url, out=True)
		else:
			print("Error: No source provided for installation.")
	elif args.command == "update":
		update()
	elif args.command == "remove":
		remove(destro=args.package_name)
	elif args.command == "search":
		if args.git:
			search(destro=args.git, out=False)
		elif args.url:
			search(destro=args.url, out=True)
		else:
			parser.print_help()
	elif args.command == "list":
		list()
