Make script more modular

While the building system is not ready for #4692 , we can start moving the code already.
When #4692 gets reopened other PRs touching script can be rebased on top of this one and decrease the chances of them being breaking/getting broke by 4692.
@sipa @jtimon See #4881 for a cleanup ;). Couldn't resist.... perhaps just base #4755 on that?