refactor temporary file cleanup and make it more consistent
legacy/trac#23271 (moved) is an example of a temporary file that doesn't properly get cleaned up. We should consider refactoring the creation and destruction of temporary files so they get cleaned up consistently.