The gunman who opened fire on worshippers at a church service on Sunday escaped from a mental health facility five years ago after being caught sneaking weapons on to a military base and planning to carry out death threats made to his commanding officers.

Devin Kelley was stationed at Holloman air force base in New Mexico, where he worked in logistics and faced a court-martial in 2012 after repeated assaults on his then wife and young stepson.

He was placed in the Peak Behavioral Health Services hospital in Santa Teresa, just across the state line from the Texas city of El Paso, but escaped and was detained without incident by police at El Paso’s Greyhound bus station, according to an investigation report obtained by KPRC local news in Houston.

Officers were advised that Kelley “was a danger to himself and others as he had already been caught sneaking firearms” on to the base, the report states, adding that he “was attempting to carry out death threats made on his military chain of command” and was also facing charges related to the assaults. He had been reported missing late one evening in June 2012. Police suspected he was planning to take a bus.

Months after the attempted escape, late in 2012, he was sentenced to a year in a military prison. After a bad conduct discharge in 2014, Kelley moved to Colorado, where he was cited on an animal cruelty charge for allegedly beating a dog.

He remarried and moved to New Braunfels, Texas, about 35 miles from the tiny town of Sutherland Springs, where police say he killed 26 people, including an unborn child, and injured 20, at the First Baptist church before he was shot twice by a civilian and fled in his SUV. The 26-year-old was found dead a couple of miles from the scene, seemingly from a self-inflicted gunshot wound to the head.

A couple who survived, Joaquin Ramirez and his partner, Roseanne Solis, told KSAT local news that after an initial hail of gunfire, Kelley went through the church shooting anyone who made a noise, including children.

Law enforcement agencies are trying to determine a motive for the mass slaughter, and on Monday said that there was a “domestic situation” that included threatening text messages to his mother-in-law, who was known to attend the church but was not present on Sunday.

Investigators have so far been unable to access Kelley’s phone because of its security protections and have sent it to FBI headquarters in Virginia, Chris Combs, an FBI special agent, said at a Tuesday news conference.

The US air force said in a statement on Monday that the base failed to enter the record of Kelley’s domestic violence conviction into the national background check system for firearms sales. Had they done so it would have raised red flags when he attempted to buy guns. A Bureau of Alcohol, Tobacco, Firearms and Explosives official said on Monday that Kelley purchased four guns between 2014 and 2017; he had a rifle and two handguns with him on Sunday.