/**
 * 
 */
package badpenguin.dkim.test;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.PrivateKey;

import badpenguin.dkim.CanonicalMethod;
import badpenguin.dkim.DkimException;
import badpenguin.dkim.ErrorType;
import badpenguin.dkim.Signer;


/**
 * A simple utility which can be used for signing email messages.
 * 
 * @author Mark Boddington &lt;dk_NO_im@_SP_bad_AM_penguin.co.uk&gt;
 *         <br>http://www.badpenguin.co.uk
 */
public class SignMail {
	
	private static String keyStoreFileName = null;
	private static String keyName = null;
	private static String keyPass = null;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		SignMail sm = new SignMail();
	
		if ( args.length < 5 ) {
			System.err.println("The badpenguin.dkim.test package contains simple utilities for testing DKIM\n");
			System.err.println("Usage: SignMail <Keystore> <keyname> <password> <canonicalisation> <filename>");
			System.err.println("\tKeystore - The path of your Java KeyStore (containing the signing key)");
			System.err.println("\tKeyname - The name of your signing key");
			System.err.println("\tpassword - The password to your keystore");
			System.err.println("\tcanonicalisation - (r|s|rs|sr) simple/relaxed method for header and body");
			System.err.println("\tfilename -  A file containing the email you wish to sign");
			System.err.println("\nExample: SignMail my_store.dat mykey passw0rd r mymail.txt");
			System.exit(1);
		}
		
		keyStoreFileName = args[0];
		keyName = args[1];
		keyPass = args[2];
		
		if ( args[3].equalsIgnoreCase("r"))
			sm.run(CanonicalMethod.RELAXED, CanonicalMethod.RELAXED, args[4]);
		else if (args[3].equalsIgnoreCase("rs")) 
			sm.run(CanonicalMethod.RELAXED, CanonicalMethod.SIMPLE, args[4]);
		else if ( args[3].equalsIgnoreCase("sr"))
			sm.run(CanonicalMethod.SIMPLE, CanonicalMethod.RELAXED, args[4]);
		else
			sm.run(CanonicalMethod.SIMPLE, CanonicalMethod.SIMPLE, args[4]);
		
	}
	
	public void run(CanonicalMethod header, CanonicalMethod body, String filename) {

		FileInputStream msg = null;
		FileInputStream store = null;
		try {
			store = new FileInputStream( keyStoreFileName );
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		KeyManager km = new KeyManager(store, keyPass);
		PrivateKey key = km.getKey(keyName);
		
		try {
			
			Signer sig = new Signer("test1", "badpenguin.co.uk", "rsa-sha256", key);
			sig.getDkimSignature().setHeaderMethod(header);
			sig.getDkimSignature().setBodyMethod(body);
			sig.getDkimSignature().setItag("dkimadmin@badpenguin.co.uk");
			sig.setAutoHeaders(true);
			sig.setAutoTimeStamp(true);
			//sig.setAutoExpire(true);
			msg = new FileInputStream(filename);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			
			sig.signMail(msg, bos);
			System.out.print(bos);
			msg.close();	
			
		} catch (DkimException d) {
				
			try {msg.close(); } catch (Exception e) { };
			
			if ( d.getErrorType() == ErrorType.NOSIG) {
				// No signature, 
			} else if ( d.getErrorType().equals(ErrorType.TEMPFAIL))  {
				// message failed, but may succeed later
				System.err.println("TEMPFAIL -- " + d.getError().getStatus());
				System.err.println(d.getError().getDescription());
				System.err.println(d.getMessage());
				d.printStackTrace();
			} else if ( d.getErrorType() == ErrorType.PERMFAIL) {
				// message failed and will never verify
				System.err.println("PERMFAIL -- " + d.getError().getStatus());
				System.err.println(d.getError().getDescription());
				System.err.println(d.getMessage());
				d.printStackTrace();
			} else {
				// Internal Library Error
					System.err.println(d.getError().getStatus());
				System.err.println(d.getError().getDescription());
				System.err.println(d.getMessage());
				d.printStackTrace();
				}
		} catch ( Exception e) {
			e.printStackTrace();
		}
	}


}
