Hey man,
This caught my eye, trust me.. you don't want a script for this!! Mgmt will get messy... Instead you simply have to set your domain to a wildcard DNS entry then it's a one liner to get the name of the sub domain in your code. I have a putt loads of examples in production, happy to share.
Cheers,
Andrew