Managing failover for MySQL nodes using HA Proxy
There is a 'backup' option that you can use in HAProxy that does what you are after. e.g. if M1 fails, use the the backup (M2)

https://www.haproxy.com/blog/failover-and-worst-case-management-with-haproxy/

Then once M1 is available again, it redirects back to M1.

n.b. you do of course need to think about replication delays, as you don't want to redirect back to M1 if it is an hour behind M2 when it comes back up. We use something like this to achieve it:

http://sysbible.org/2008/12/04/having-haproxy-check-mysql-status-through-a-xinetd-script/