--with-statedir compile time option

Mostly interesting to package mantainers but there is some cleanup here as well.

This is the continuation of #1400 and it's ready for review.