CAIRO – After months of unrest that have brought his country to the edge of civil war, Yemen President Ali Abdullah Saleh signed an agreement in Saudi Arabia on Wednesday to hand over power to his vice president in a deal that leaves him immune from prosecution in the deaths of protesters.

The agreement reached with the opposition and backed by the U.S. and Persian Gulf nations allows Saleh to retain the title of president for three months while early elections are scheduled.

A clever politician who has ruled for 33 years, Saleh has broken similar promises before and it remains to be seen if he will finesse a loophole to stay in charge.

His possible departure will leave his poor and battered nation facing an uncertain fate as tribes position for power, a secessionist movement rumbles in the south and a resurgent al-Qaida branch battles security forces in towns and villages.

Saudi television showed Saleh signing the agreement, negotiated by a United Nations envoy Jamal, Benomar, in the presence of Saudi King Abdullah.

Even as the deal was finalized, Saleh’s army battled fighters from a rival tribe.

The city has become a war zone of barricades, tanks and competing factions playing out against a peaceful anti-government protest movement that includes human rights leader Tawakul Karman, co-winner of this year’s Nobel Peace Prize.