Hi there,
no complete solution.
I am not a fan of reinventing the wheel, so maybe take a look at the dbatools cmdlets
Especially
http://docs.dbatools.io/#Invoke-DbaAgFailover
That would at least help to failover your availability group(s) easily.