How to use Nvidia Optimus to switch active GPUs and save power on Linux laptops

Nvidia's power-saving Optimus technology is available on Linux, but the experience is far from smooth out of the box. Here's how to fix it.