import os

def update_makefile(makefile_path, po_dir):
    # Get the base names from the .po files
    base_names = sorted([os.path.splitext(po_file)[0] for po_file in os.listdir(po_dir) if po_file.endswith('.po')])

    # Prepare the install and uninstall lines
    install_lines = ["\t" + f"cp -R resources/txts/translations/{lang} /usr/share/locale/" for lang in base_names]
    uninstall_lines = ["\t" + f"rm /usr/share/locale/{lang}/LC_MESSAGES/kickshaw.mo" for lang in base_names]

    # Read the original Makefile
    with open(makefile_path, 'r') as file:
        lines = file.readlines()

    # Update the Makefile
    with open(makefile_path, 'w') as file:
        in_install_section = False
        in_uninstall_section = False
        for line in lines:
            if line.strip() == "install:":
                in_install_section = True
                file.write(line)
                file.write("\tmkdir -p /usr/share/locale\n")  # Keep the initial line of install section
                file.writelines([line + '\n' for line in install_lines])
                file.write("\tcp kickshaw $(PREFIX)/bin\n")  # Keep the final line of install section
                continue

            if line.strip() == "uninstall:":
                in_install_section = False
                in_uninstall_section = True
                file.write(line)
                file.write("\trm $(PREFIX)/bin/kickshaw\n")  # Keep the initial line of uninstall section
                file.writelines([line + '\n' for line in uninstall_lines])
                file.write('\t@echo "For every user who has started Kickshaw a settings file .kickshawrc was created inside the respective home directory. It is not removed automatically, so it has to be removed manually."\n')  # Keep the final line of uninstall section
                continue

            if in_install_section and line.startswith('\t'):
                continue
            elif in_uninstall_section and line.startswith('\t'):
                continue
            else:
                in_install_section = False
                in_uninstall_section = False
                file.write(line)

# Example usage
makefile_path = '../Makefile'
po_dir = '../po'
update_makefile(makefile_path, po_dir)
