When the Qajars had succeeded in restoring the unity of Persia, the sons of the Khan were no more able to maintain their independence like the other Caucasian chiefs and had to choose between Russia and Persia.[1] The Khan of Shirwan, Mustafa, who had already entered into negotiations with Zubov, submitted to the Russians in 1805, who occupied the Persian cities of Derbend and Baku the next year (1806) during the Russo-Persian War (1804–1813), but soon afterwards he made overtures to the Persians and sought help from them.[1] By the Treaty of Gulistan (12/24 October 1813) following the end of the 1804–1813 war, Persia was forced to cede its territories and regions comprising Darband, Quba, Shirwan and Baku, while giving up all claims on them as well.[1] Nevertheless, Mustafa continued to have secret dealings with Persia. It was not until 1820 that his territory was occupied by Russian troops; the Khan fled to Persia and Shemakha was irrevocably incorporated in Russian territory.[1] Iranian anger while being dissatisfied with losing swaths of its integral territories in the North and South Caucasus subsequently sparked the Russo-Persian War (1826–1828), which resulted in another Iranian loss, as well as the ceding of its last remaining territories in the Caucasus comprising what is now Armenia, and southern parts of the contemporary Republic of Azerbaijan. The Treaty of Turkmenchay of 1828 officially ratified the forced ceding of these Iranian territories to Imperial Russia, while it would also mark the official end of millennia long intertwined Iranian hegemony, rule, and influence over the Caucasus region, including Shirvan.