Dear Rij,
An interesting if not complicated question. I'm not sure how you could do this programatically, but I would suggest posting the question in the developer's forum.
However, I do think that this could be dangerous if things went wrong. Would it not be better to customise 'MyMoodle'?
Cheers,
Gareth