In 1807 a pact was signed between France and Spain; the Fontainebleau Treaty in name of the Spanish king Charles IV by Manuel Godoy and Napoleon Bonaparte. They agreed to a joint military invasion of Portugal, which would allow the French troops to cross Spain to get to Portugal, which was allied with Great Britain. It would become one more conflict episode in Spain and Portugal's history.
At the time Portugal was ruled by the House of Braganza, particularely by Prince John as regent in his crazy mother's stead. While Spain and France were allies, and Napoleon was trying to get hegemony of the European continent. The English were powerful contenders though.
The treaty stipulated that once Portugal was successfully invaded, the country would be divided in three parts. The north would be given to Carlos Luis I de Borbón, the former King of Etruria (Italy) in compensation for his Italian territories ceded to Napoleon.
The middle part would be perhaps serve as a possible exchange for Gibraltar and Trinidad Island in British hands and the south part would go to Godoy, who represented the King in the treaty as Princedom of Algarve. The division of Portugal was agreed. How its colonies would be divided was yet to be decided.
After only a few days Spain had taken over Oporto from the north and Setúbal from the south, with most of their troops in Portugal and out of Spain. In the meanwhile the French troops crossed Spain and the Portuguese frontier and arrived in Lisbon on November.Prince John, who would later become JohnVI, departed to Brazil with an entourage of thousands of people where he would establish his court. Once in Brazil his troops occupied French Guiana and attacked Uruguay
Despite victory, it was quite a lesson for the Spanish though as the presence of French troops in the country continued to grow each day and instead of going on their way to Portugal they occupied several locations of the country. They people became more and more alarmed as they increasingly felt this "friendly" occupation, with more than 60,000 French soldiers in Spain, as a growing threat. Rather an unexpected turn in Spain and Portugal's history.
Of course, Spain got nothing of what had been agreed in the division of Portugal
In 1807 the mutiny of Aranjuez took place, which resulted in Carlos IV's abdication and Fernando VII rose to the throne. He still believed the French emperor would respect the treaty. However Bonaparte tricked him when he called Fernando and his parents to Bayonne. Carlos IV abdicated in favour of his son, and Bonaparte, who knew how to play dirty, gave the crown to his own brother Joseph Bonaparte I. This would lead to the war known as War of Independence.