I would look at software such as NOOBS in Github
and modify that so it looks for a new OS and updates it.
You do realise that ALL programs loaded by APT / PIP etc and any data created will be wiped as well as the OS don't you?
You could look to get very cleaver and mount the home folder on another partition and auto-reinstall the programs / data files but this is no minor task to do via a manually created program.
I would look to use something like Puppet for the configuration or possibly FAI (Fully Automatic Installation) for OS and config.
edit: Added link to NOOBs in GITHUB and removed waffle
Need Pi spray - these things are breeding in my house...