Best way for a perfect fit is to spile it.
There are various ways, yuo can fit a template board roughly to size, (and I do mean roughly!) or you can tack a few strips of ply/MDF to make up a rough shape close to what you need.
If the shelf is on battens, rest the template on this, and using a piece of timber or similar that spans the gap between template and wall and make a series of marks to indicate all the high and low spots, along with intermediate marks, pipes etc. (I usually use a Formica sample. An old credit card does a good job as well)
Drop the template onto the work, and using the card/block, align it with the marks and replicate the positions by making a line at the opposing edge of the card/block.
If the marks are made close enough, and inch or so apart, you can simply freehand join them if needed.
You can make a solid scribe line initially, but I find a series of marks just as effective. It looks like a load of running stitches on the template piece once fully marked.
Once cut, it should drop in perfectly to the position it was marked from, needing no additional fitting.
It's a method used in boatbuilding to work out the curvature of planking around the frames where you have curves as well as twists to contend with, but have to cut them from a flat board before steaming them into place,and works equally well on flat stuff like shelves into alcoves etc.
you can do similarly with a pair of compasses or dividers, but any discrepancy away from 90 degrees to the position taken will be replicated on the final piece which is why I stick to my formica sample.
cheers,
Andy