Generation of mesoscopic entangled states in a cavity coupled to an atomic ensemble