He was shocked during the war (most likely by the death of his loved one) and that sent him into insanity. He then figured out Madaras goals somehow and decided that the only way to stop death and destruction is to have one person in control of everything. He then started travelling, gaining knowledge. On his travels he encountered Zetsu and promised Zetsu something but in return Kagami asked for his complete loyalty. He then thought out his plan. He would assume the identity of Madara to strike fear into his enemies. He also found Madaras body and stole the Rinnegan, he then gave it to a young boy from Amegakure named Nagato and formed a seal on him so that he would not remember a thing. This then all leads to the point where we are at know.