Based on https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/4975 (thanks @sheerun) with small changes on top
cc @iamphill @tauriedavis