Legally speaking, the courts have no choice but to legalize same-sex marriage. The government has been meddling in the marriage business since at least the 1860's in the U.S. in an effort to control who can marry whom. It has also been tying government benefits to marriage status, which, when the equal treatment clause of the 14th Amendment is applied, created the political quagmire that we find ourselves in today.
If the government would just get out of the marriage business altogether and return the institution to the churches, where it once belonged, then there would be no problem. There are religious institutions who are willing to perform same-sex marriages, so none would be denied their choice to marry. By getting out of the marriage business, the government can effectively solve the entire problem without actually threatening the religious aspects of marriage.
The only other solution,which does not present the possibility of the government infringing on religious liberties, would be to require civil marriages of all people, then they could perform any religious ceremony that they wish.