That reminded me of this which I wrote many years ago:
(only the top commit - the rest is old and outdated, and already merged in some form. Simply included because it was in my old devel branch and rebasing without fixing makes no sense)
Posted now in case it is useful as a starting point for someone. Needs some love, and I'm unable to provide that. All I know is that I tested it and it worked back when it was written