RIO DE JANEIRO — A man opened fire in a cathedral in southern Brazil after Mass on Tuesday, killing four people and wounding four more before taking a bullet in the ribs in a firefight with police and then shooting himself in the head, authorities said.

The shooting happened right after the midday service had ended at the Metropolitan Cathedral in Campinas, a city about 60 miles (100 kilometers) north of Sao Paulo.

"It's so sad," said Wilson Cassante, a press officer with the archdiocese. "It's hard to imagine the pain this has caused."

Hours after paramedics were seen taking bodies and injured out of the church, authorities identified the shooter as 49-year-old Euler Fernando Grandolpho from Valinhos, a nearby city in the densely populated state of Sao Paulo.

Grandolpho, a systems analyst, was not a member of the church, authorities said. According to public records, he had held various jobs with government entities, including a stint as an assistant to the prosecutor in the public ministry in Sao Paulo.

Authorities said they had not determined a motive. A backpack found near the dead gunman had his identification but no note or other clues, police investigator Jose Henrique Ventura told reporters outside the church.

"Thanks to the intervention of police, something much bigger was avoided," Ventura said, adding that the four injured were in stable condition.

Danielle Coutinho told EPTV that she was sitting in the church chatting after Mass when gunfire began. A man sitting close to her was shot as she and others ran.

"I saw people getting shot. I can't get it out of my head," she said in tears. "It was horrible."

Brazil has long struggled with gun violence, and is routinely the world leader in total homicides, though mass shootings are rare. Last year, nearly 64,000 people were killed. President-elect Jair Bolsonaro, a former army captain, campaigned on promises to crack down on violence, in part by loosening gun laws so more civilians could arm themselves.

Hamilton Caviola Filho, a police investigator, told news portal G1 that authorities had reviewed surveillance footage from inside the cathedral.

The shooter "came into the church, sat on a pew, with time to think, and then got up and starting shooting," Caviola Filho said.

The investigator also said that before shooting himself in the head, the suspect took a bullet in the ribs from responding police. In total, the suspect fired at least 20 shots, Caviola Filho said.

Father Amaury Thomazi, who celebrated Mass before the shooting, posted a video recounting the chaos that followed the burst of gunfire.

"Nobody could do anything or help in any way" to stop the rampage, Thomazi said. He called on people to pray for the dead, the injured and the shooter.