Is there a way to turn off categories and subcategories where all products in those groups are inactive?

I know I can click on the green button and do it but I'm looking for a way to automate it with mysql statement or by modifying the php code in one of the files.

Thanks.