The man critically shot after allegedly attacking a police officer with a hammer in Midtown has a history of mental illness and disturbing social media trail, officials said Wednesday.

David Baril, 30, was shot four times around 10 a.m. in the area of West 37th Street and Eighth Avenue, and is in critical but stable condition at Bellevue Hospital.

Police Commissioner Bill Bratton said Baril was believed to be behind four random hammer attacks throughout the day on Monday.

The NYPD released video of the encounter, which was over within seconds, just hours after the shooting.

Bratton said Baril was identified by the departments facial recognition technology earlier in the week, and his photo was distributed to police officers on patrol. Baril was spotted by Officer Lauren O’Rourke and Geraldo Casaigne, who followed him for about a block. When Baril realized he was being followed, he took out a hammer and started hi tting O’Rourke with it, Bratton said.

Casaigne shot Baril three or four times in the head, torso and right arm, Chief William Aubry said.

“He will not be on the streets attacking innocents any longer,” Bratton said, and that both “veteran officers” acted “professionally and heroically.”

Baril, from the Bronx, is a paranoid schizophrenic believed to be living on the streets. His last address was at a mental health facility in Upper Manhattan, which he voluntarily left in January. He has eight prior arrests in New York City, including an attempted assault on a police officer in 2013, possession of cocaine and a stun gun.  

 Bratton said Baril had a disturbing social media history, including an Instagram drawing of a hammer dripping blood. His account has numerous drawings Baril calls “devils,” and a photo shows him wearing a camouflage face mask similar to one recovered by police at the scene.