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.
This should be fixed in master by 3a757c52947a5a1beefb456ca7d3ebab7a5a14a2.