There is a stencil_export extension (possbily created by AMD) that allows a shader to modify the stencil buffer directly. Therefore, if you can access that, you just need to create another frame buffer and use the previous FBO’s colour attachment as an input texture to the shader. Just check that texture2D (FBOsampler, texcoord).a = some value and you’re good to go.
You can bind it as a uniform sampler2D and sample that texture. You are going to get the values as 0.0 to 1.0 with 1.0 being the far plane and 0.0 being the near plane.