import requests
import os
import configparser
from configparser import ConfigParser
def main():
    ini = str(input("Please select an ini file: "))
    response = str(input("Do you wish to install files from "+ini+"(please enter 1), or do you wish to add new links to "+ini+"(please enter 2)? "))
    if response == "1":

        config = configparser.ConfigParser()
        config.read(ini)

        section_name = 'links'
        if section_name in config:
            items = config.items(section_name)
            links_list = [value for key, value in items]
            print(links_list)
        else:
            print(f"Section '{section_name}' not found.")

        def download_file(url, destination_folder):
            """
            Downloads a file from a given URL to a specified destination folder.

            Args:
                url (str): The URL of the file to download.
                destination_folder (str): The path to the folder where the file should be saved.
            """
            try:
                # Create the destination folder if it doesn't exist
                os.makedirs(destination_folder, exist_ok=True)

                # Get the filename from the URL
                filename = os.path.basename(url)

                # Construct the full path for saving the file
                file_path = os.path.join(destination_folder, filename)

                # Send a GET request to the URL
                response = requests.get(url, stream=True)
                response.raise_for_status()  # Raise an exception for bad status codes

                # Write the content to the file in chunks to handle large files
                with open(file_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        f.write(chunk)

                print(f"File '{filename}' downloaded successfully to '{destination_folder}'")

            except requests.exceptions.RequestException as e:
                print(f"Error downloading file: {e}")
            except Exception as e:
                print(f"An unexpected error occurred: {e}")


        # Example usage:
        target_directory = "./Downloads"  # Replace with your desired path

        for link in links_list:
            download_file(link, target_directory)
        directory = os.getcwd() + "\Downloads"
        for name in os.listdir(directory):
            if name.lower().endswith('.exe'):
                os.startfile(directory+"\\"+name)
        main()

    elif response == "2":
        config1 = ConfigParser()
        config1.read(ini)
        section_Name = 'links'
        while True:
            all_keys = []
            if section_Name in config1:
                for key in config1[section_Name]:
                    all_keys.append(key)
            length = len(all_keys) + 1

            new_key = str(length)
            new_value = str(input("Please input the link you would like to add, please enter 1 to leave: "))
            if new_value == "1":
                main()
            new_value = new_value.replace("%", "%%")

            if not config1.has_section(section_Name):
                config1.add_section(section_Name)

            config1.set(section_Name, new_key, new_value)
            with open(ini, 'w') as configfile:
                config1.write(configfile)

main()