To modify Masterpages, I'd recommend taking a look at these two resources.
First, a blog post that explains how to apply master pages:
arichterwork.blogspot.com/2008/03/programmatically-inherit-master-page.html
E.g. web.MasterUrl = "/_layouts/custom.master"
Next the SharePoint JavaScript API reference on Core objects, the Web in this case:
msdn.microsoft.com/EN-US/library/office/jj245288.aspx
You can see that both masterUrl and customMasterUrl are available R/W.
Finally, you'll want to do some basic file manipulation. Here are the MSDN resources:
msdn.microsoft.com/en-us/library/jj163201.aspx#BasicOps_FileTasks
There are two more challenges. The first is about permissions: updating the masterpage gallery is a high privilege operation. The other, riskier, challenge here is that you're injecting JS into pages, and JS can be used maliciously.
If you planned to use this approach with an app for SharePoint, I'd consider finding an alternative approach. Script injection like this is not permitted.