<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def cleanup():
 """Must be called before exit"""

    temp_dirs = []
    for key in ('headless', 'headed'):
        if FIREFOX_INSTANCE[key] is not None:
            if FIREFOX_INSTANCE[key].profile:
                temp_dirs.append(FIREFOX_INSTANCE[key].profile.profile_dir)
            try:
                FIREFOX_INSTANCE[key].quit()
                FIREFOX_INSTANCE[key] = None
            except:
                logger.exception(
                    "Exception occurred in browser cleanup"
                )
    for temp_dir in temp_dirs:
        shutil.rmtree(temp_dir, ignore_errors=True)