A drug-abusing former Somerville cop was caught on video breaking into headquarters and stealing a commanding officer’s sidearm, according to prosecutors and police reports.

Samuel Hayward Stanford, had been fired July 23 for abusing opioids, pleaded not guilty in Somerville District Court to charges of breaking and entering in the nighttime, drug possession and possession of ammunition without an FID card. He was held on $25,000 cash bail.

The gun he stole, Somerville police Lt. Joseph McCain’s department-issued .40-caliber Sig Sauer, has been recovered, assistant Middlesex District Attorney William Freeman said.

“The matter remains under investigation,” Freeman told First Justice Maurice R. Flynn II.

In Stanford’s apartment, police said they found Somerville police uniforms, citation booklets, three boxes of .40-caliber ammo, a .38-caliber Smith & Wesson handgun, two bags of heroin, and a lock box stashed in a hamper of dirty clothes that contained 173 Percocet tablets, $20,000 cash and another box of .40-caliber ammunition. The box was found between two twin beds in the room Stanford shared with his younger brother, Edward Reis Stanford, 25.

Edward Stanford today pleaded not guilty to drug possession and possession of ammunition without an FID card. He was held on $500 cash with the stipulation that if he posts bail he will be on supervised probation.

Samuel Hayward Stanford faces 20 years in state prison if convicted, and Freeman suggested more charges could be pending.

Samuel Stanford’s public defender Rachel Scotch said her client sought out treatment for his drug problem even before it cost him his job.

He was appointed to the Somerville Police Department by Mayor Joseph A. Curtatone in May 2013. His brother is unemployed, the criminal complaint against him states.

Scotch vehemently objected to Samuel Stanford being brought before news cameras, arguing there is an identification issue in the breaking and entering case; however, Freeman said he’s already been identified on the surveillance video by several police officers.

“They knew him and worked with him,” Freeman told Flynn.

The Aug. 3 video, according to court documents, shows Samuel Stanford entering a rear entrance of police headquarters just after 8:35 p.m. and proceeding to a men’s locker room, where he was out of camera range for six minutes.

When he returned, police said, “there was a noticeable ‘heavy looking’ bulge, consistent with the shape, size and weight of a .40 caliber gun, in Stanford’s right pocket.”

Freeman said Samuel Stanford used a key code to get into the building and a piece of cloth once inside.

“He basically rigged the doors so they wouldn’t lock,” the prosecutor said.

McCain reported his gun missing the following day.