A prisoner at Guantanamo Bay is to be released after a judge ruled that he had been held there illegally for more than six years.