

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Scanner;

import os.path.Pathutil;

public class CertRenewRunner
{

	public static void main(String[] args) throws Exception
	{
		ArrayList<AppBackupData> apps = new ArrayList<AppBackupData>();
		DirectoryStream<Path> directory = Files.newDirectoryStream(
				Pathutil.expanduser( "~/Desktop/backup" ).toPath() );
		for ( Path appbackup : directory )
		{
			if( appbackup.toFile().isDirectory() )
			{
				try
				{
					AppBackupData backupObj = new AppBackupData( appbackup.toFile() );
					apps.add( backupObj );
					if( backupObj.getId() == null) {
						//TODO move this
						throw new Exception("oops - missing? " + appbackup.toFile().toString());
					}
				}
				catch (IOException e)
				{
					System.err.println( appbackup.toFile().toString() );
					e.printStackTrace();
				}
			}
			Collections.sort( apps );
		}
		for ( AppBackupData app : apps)
		{
			System.out.println( app.toString() );
		}
		System.out.println( "\nNow renewing... old certs will be removed from keychain or it will export old ones.\nQuit Keychain now.\n");
		System.out.println( "How many (starting at oldest, top) should be renewed?" );
		Scanner in = new Scanner(System.in);
		int todo = in.nextInt();
		int total = todo;
		for ( AppBackupData app : apps)
		{
			System.out.println( "\n" );
			System.out.println( app.toString() );
			iTunesDeveloperInterface devBrowser = new iTunesDeveloperInterface( app );
			devBrowser.renewPushCert();
			devBrowser.close();
			
			if( --todo < 1) break;
		}
		System.out.println("\nCertificates.p12 created in the folders, for the "+ total + " oldest certs on record. ADD TO SNS!!");
		//iTunesDeveloperInterface browser = new iTunesDeveloperInterface(apps.get(0));
	}

}
