Fix order of before and after hooks.

Also fix passing arguments to tasks executed by before and after hooks.

This fixes both issues and has tests, although somewhat weird tests. I would prefer this was refactored, but I'm almost running out of time to work on this.

Bug report was #1004 and original pull request was #928.