def convert_to_in_target(bash_script_path, target_username, output_file_path):
    try:
        with open(bash_script_path, 'r') as file:
            lines = file.readlines()

        in_target_commands = []

        # Construct the script creation command
        script_creation_cmd = f"d-i preseed/late_command string \\"
        in_target_commands.append(script_creation_cmd)

        # Convert each script line into an in-target command
        for line in lines:
            # Strip the line to remove leading/trailing whitespace
            stripped_line = line.strip()
            if stripped_line:  # Ignore empty lines
                escaped_line = (
                    stripped_line.replace('"', '\\"')
                                .replace('$', '\\$')
                                .replace('(', '\\(')
                                .replace(')', '\\)')
                                .replace('[', '\\[')
                                .replace(']', '\\]')
                                .replace('#', '\\#')
                )
                cmd = f"in-target bash -c 'echo \"{escaped_line}\" >> /home/{target_username}/post_hardware.sh' \\"
                in_target_commands.append(cmd)
        
        # Add command to make the script executable
        in_target_commands.append(f"in-target chmod +x /home/{target_username}/post_hardware.sh")
        
        # Write the generated in-target commands to the output file
        with open(output_file_path, 'w') as output_file:
            for command in in_target_commands:
                output_file.write(command + "\n")

        print(f"In-target commands successfully written to {output_file_path}")

    except FileNotFoundError:
        print("The specified bash script file does not exist.")

# Usage
bash_script_path = 'late_command.sh'  # Replace with the path to your bash script
target_username = 'computerspende'  # Replace with the target user's username
output_file_path = 'scripts.txt'  # Replace with the desired path for the output file
convert_to_in_target(bash_script_path, target_username, output_file_path)
