Gracefully shutdown the agent on SIGTERM. Fixes #1675

Tested on Ubuntu precise. Fixes github issue #1675