various build system improvements/fixes

Merging this would make life of a gentoo packager easier. If you think something is wrong you can cherry-pick the commits.