Partially based on CMaNGOS' script (cherry picked from commit d37fba1a6feb04b5afcf4341f56d73fadbddbaf0)