In the ruins of a dusty al Qaeda compound in Ayub Kheil, a remote village in Afghanistan, 15-year-old Canadian-born Omar Khadr secured his position behind a crumbling, bullet-riddled wall and threw the Russian grenade that would change his life forever.

It landed him a decade behind bars in Guantanamo Bay, Cuba — as the detention center’s young­est prisoner — where he claimed he was tortured. It also put him at the front and center of protracted legal battles in two countries.

And finally, last week, it made him a millionaire.

On Friday, the Canadian government offered a stunning apology to the former al Qaeda militant, and deposited US $8 million in his bank account.

“We hope that this expression, and the negotiated settlement reached with the government, will assist him in his efforts to begin a new and hopeful chapter in his life with his fellow Canadians,” reads the statement from the Liberal government Friday.

How Omar, now 30, went from al Qaeda militant to soft-spoken “victim” is a bitter controversy that has divided a country for more than a decade.

Some consider him the survivor of the worst kind of abuses — a helpless child forced into conflict by a fundamentalist father. But others see him as a hardened terrorist and coldblooded killer.

“This payout is a slap in the face to men and women in uniform who face incredible danger every day to keep us safe,” Canadian Conservative leader Andrew Scheer said.

He certainly had the terrorist’s pedigree.

Omar Khadr was born in Toronto on Sept. 19, 1986, the son of a Palestinian mother and an Egyptian father who had deep ties to the Muslim Brotherhood and would later become one of Osama bin Laden’s most trusted lieutenants. After 9/11, the FBI added the elder Khadr to its list of most wanted for the attacks on the World Trade Center and the Pentagon.

Omar was the third son, and grew up with four brothers and two sisters, shuttling between his maternal grandmother’s home in a down-at-the-heels Toronto suburb and a home in Peshawar, Pakistan, where his father Ahmed Khadr ran charities, some of which were used to funnel money to terrorists.

In 1995, Ahmed was arrested in Pakistan on charges that he financed the bombing of the Egyptian Embassy in Islamabad that killed the suicide bomber and 16 others. At the time of the attack, his eldest daughter, Zaynab, was engaged to Egyptian Khalid Abdullah, who was accused of buying one of the trucks used in the attack.

Ahmed proclaimed his innocence, and went on a hunger strike that put him in a hospital.

News photographs show Omar, then a curly-haired 9-year-old, at his father’s hospital bedside as the family tearfully appealed to the Canadian government for his release.

In a remarkable precursor of what was to happen to Omar more than two decades later, the Canadian government rallied ­behind Ahmed as one of its own — never mind that he was a suspected terrorist.

Prime Minister Jean Chrétien, then on a trade mission to Pakistan, intervened with Prime Minister Benazir Bhutto on Ahmed’s behalf. Ahmed was released a few months later. When he and his family got off the plane in Toronto, Ahmed kissed the ground.

But the family didn’t stay in Canada for long. Soon they returned to Pakistan, where Ahmed resumed his “charitable” work, building connections with the Taliban and al Qaeda.

“While traveling with his father, Omar saw and personally met senior al Qaeda leaders, including Osama bin Laden, Dr. [Ayman] Zawahiri, Muhammad Atef and Sair al Adel,” the US military said.

Zawahiri, al Qaeda’s military strategist, is today the leader of the group. Atef was the military head of al Qaeda before he was killed in a US drone strike in 2001 and al Adel was indicted for the 1998 attack on the US Embassy in Kenya that left more than 200 dead. He is still at large.

The family also lived in the bin Laden family compound in Jalalabad where Omar and his brothers were sent to al Qaeda training camps.

According to US and Canadian security forces, Ahmed was one of the main financiers of those camps. A month before he joined an al Qaeda cell in 2002, Omar was sent by his father for private instruction in explosives and combat, according to the military.

The plan was for Omar to join a cell made up of al Qaeda and the Libyan Islamic Fighting Group as a fighter and translator, since besides English, he speaks Pashto, Arabic, Dari and some French.

Omar learned to launch rocket-propelled grenades and became skilled at planting improvised explosive devices that were used to blow up US armored vehicles in Afghanistan. Amid the rubble at the Ayub Kheil compound, US Special Forces unearthed videos showing Omar and another al Qaeda operative planting roadside bombs in Afghanistan.

He also collected intelligence on US troop movements near the airport in Khost, Afghanistan, ­according to the US military.\

“Omar Khadr did not wear a uniform and attempted to blend in with the civilian population in order to gain as much actionable intelligence as possible.”

Omar’s stint fighting for al Qaeda lasted all of two months. Certain he was about to die in the besieged compound on July 27, 2002, he felt he had nothing to lose by throwing the grenade that ended up killing a US Army medic and wounding another soldier, according to court documents.

Nearly a year into the war against the Taliban and al Qaeda in Afghanistan, US Special Forces had surrounded the al Qaeda compound near the Pakistani border where Omar was holed up with several militants. When the Americans sent in two Afghan soldiers to negotiate the surrender, Omar’s al Qaeda comrades responded by shooting them dead.

An intense, four-hour firefight followed. As the militants lobbed grenades, US forces called for ­reinforcements. Within minutes, Apache attack helicopters dropped explosives, including two 500-pound bombs, and fired thousands of rounds of ammunition into the mud-brick fortress.

When the shooting stopped, a group of US soldiers moved in to assess the damage and look for the wounded.

“Khadr was not under the impression that US soldiers were preparing to charge his position, attack or engage him. Rather, Khadr thought that the soldiers entering the compound were looking for wounded or dead and that the firefight was over,” military court documents state.

Omar, the only survivor, waited until the soldiers approached him before throwing the Russian F-1 grenade. He later told military ­interviewers that he was on a suicide mission “to kill as many Americans as possible” before being killed himself.

The grenade exploded near Sgt. 1st Class Christopher Speer, “launching shrapnel into his head and causing mortal brain damage,” the US military says.

Speer died 12 days later, a month shy of his 29th birthday, leaving behind a young widow, a 3-year-old daughter and a 10-month-old son.

Another soldier, Layne Morris, was wounded and lost an eye.

Omar was shot twice in the torso and suffered damage to the eyes. He was rushed to Bagram Air Force Base, where an ophthalmologist was specially flown in to save his eyesight.

Weeks later, when told that he had killed Speer, “Khadr stated that he felt happy when he heard that he killed an American.”

“Khadr indicated that when he would get ‘pissed off’ with the guards at Bagram, he would recall killing SFC Christopher Speer and it would make him feel good,” according to military-trial documents.

Omar was later transferred to Guantanamo and held in solitary confinement in Camp 5, the maximum-security complex, where he claims he was sleep-deprived and threatened with gang rape by his interrogators. He also claimed that he was isolated and desperately missed his family.

At one point in March 2004, when he was given a photograph of his family by a Canadian consular official who flew to visit him, he was left alone in the interrogation room. After reportedly urinating on the photograph twice, he laid his head next to the picture in “an affectionate manner,” noted an observer.

“He was lost,” his Canadian lawyer, Dennis Edney, told Canada’s Maclean’s magazine. “No one had touched him in years, so I hugged him.”

In October 2010, Omar confessed to murder before a US military tribunal at Guantanamo, where by that point he had been held for nearly eight years. He was the prison’s youngest inmate.

The confession was part of a plea deal that would let him return to Canada, where the country’s highest court had unanimously ruled that the Canadian government did not do enough to protect the teenager’s human rights while he was incarcerated at Guantanamo.

The court said his constitutional rights were violated when Canadian security agents interviewed him “under oppressive circumstances” in Guantanamo in February 2003 and shared the information with US investigators.

Canada’s Liberal government formally apologized Friday to Omar, who now towers more than 6 feet, with a solid build and a full beard. He is a free man, and lives near his longtime lawyer in Edmonton.

On Wednesday, he received a check for $8 million from Canadian taxpayers. The cash was transferred quietly in order to prevent the families of Speer and Morris from seeking an injunction and possibly collecting on the settlement, according to a ­Canadian press report.

Speer’s widow had recently filed an injunction in Ontario ­Superior Court in order to block any compensation to Omar from Canada, but she was too late.

Both the Speer and Morris families sued Omar in federal court in Utah, winning a $134 million default judgment against him in 2015. They were hoping to collect part of that cash from the Canadian settlement.

Several calls and an e-mail to the families’ lawyer in Utah were not returned last week.

“It’s a real head-scratcher, let me tell you,” Morris, 55, told the Toronto Sun last week. “Typically, criminals pay for their crimes but this time we are paying the criminal for his crimes. It’s kind of ass-backwards, you have to admit.”

The payout and apology have reignited a firestorm of controversy about whether Omar was a hardened terrorist or a victim himself — forced by circumstances and a fundamentalist ­father who groomed him to ­become a child soldier.

“I heard over and over how he’s the victim,” said Speer’s tearful widow, Tabitha, addressing Khadr at his 2010 trial at Guantanamo. “I don’t see that. The victims . . . they are my children. Not you.”

A year after Omar was captured, his father was killed in a firefight at an al Qaeda compound in Waziristan, Pakistan. He was fighting alongside another son, Omar’s 14-year-old brother, Abdul Karim, who was wounded in the attack.

Despite damning evidence against him, Omar’s lawyers maintain he is a victim and that his confessions were coerced with the help of sleep deprivation, threats and solitary confinement in Guantanamo.

His defenders say he has been unfairly branded by his family’s involvement in terrorism. And ­after returning to Canada in 2012, Omar has largely recanted his confession and says he can no longer even remember throwing the grenade that killed Speer.

“There isn’t an ideological thought in Omar’s brain,” said ­Edney. “I’ve never met a more peaceful guy in my life.”

But even some Canadians find that hard to swallow.

Last week, a petition started by the Canadian Taxpayers Federation to protest the payout amassed more than 52,000 signatures in less than 48 hours. It read, in part, “Canadians should not be forced to pay millions of dollars to a killer.”