Switching Between Linear Consensus~Protocols: A Variational Approach