This is largely borrowed from Gentoo's ebuild for mercury (including the patch for the default_grade make target)