A farewell letter left by a teenage refugee who attacked passengers on a German train with an axe said Muslims needed to "defend themselves", it has emerged.

The letter was discovered in the 17-year-old's bedroom at his German foster home and is believed to have been addressed to his father.

It read: "And now pray for me that I can get revenge on these non-believers, pray for me that I go to heaven."

German investigators said it went on to describe the condition of Muslims around the world, the presence of German troops in Afghanistan and that Muslims "must defend themselves".

The attack on Monday (18 July) – which left five people in hospital, two critically injured – saw the teenager launch into a frenzied attack on a train in the Bavarian city of Wurzburg with an axe.

He was later shot dead by police after fleeing the scene and going on to attack a woman walking her dog.

The attacker was later named in German media as Riaz Khan Ahmadzai, with investigators believing he was of Pakistan origin and arrived into Germany as a refugee claiming to be from Afghanistan.

The authorities said he had been staying with a foster family in the nearby town of Gaukoenigshofen for just two weeks after residing in a refugee centre since arriving in the country last year.

A news agency closely associated with terror group the Islamic State (IS) later released a video showing what investigators believed to be Ahmadzai pledging allegiance to the jihadist group. He was referred to by the group under the nom de guerre Mohammed Riyad.

It claimed the attacker "executed the operation in response to calls to target nations in the coalition fighting the Islamic state".

Along with the letter, a hand-painted version of the IS black flag was found in Ahmadzai's bedroom. A witness also claimed to have heard the attacker shout "Allahu Akbar" during the attack.

But investigators said Ahmadzai's exact motives were not fully clear, with Joachim Herrmann, the Bavarian state interior minister, saying: "We must determine what the motive was and to what extent he really belonged to the Islamist scene or self-radicalised very recently."

Details released by police instead began to paint a picture of a teenager who may have been motivated by a desire for "revenge".

Ahmadzai had made a flurry of phone calls days before the attack, telling one person close to him that a friend of his in Afghanistan had recently been killed, the newspaper Süddeutsche Zeitung reported. The exact details of who or how this person died is not clear.

His foster mother, who has not been named, said he showed no signs of extremism.

"He was absolutely friendly and courteous," she said. "But damn it, the boy! How desperate do you have to be to do what he did? He was just a kid."