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

import java.io.FileInputStream;

import badpenguin.dkim.DkimException;
import badpenguin.dkim.ErrorType;
import badpenguin.dkim.NSKeyStore;
import badpenguin.dkim.Verifier;

/**
 * A simple utility which can be used to Verify DKIM Signatures.
 * 
 * @author Mark Boddington &lt;dk_NO_im@_SP_bad_AM_penguin.co.uk&gt;
 *         <br>http://www.badpenguin.co.uk
 */
public class VerifyMail {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		VerifyMail vm = new VerifyMail();
		if ( args.length < 2 ) {
			System.err.println("The badpenguin.dkim.test package contains simple utilities for testing DKIM\n");
			System.err.println("Usage: VerifyMail <nameserver> <filename>");
			System.exit(1);
		}
		vm.run(args[0], args[1]);
		
	}
	
	public void run(String nameserver, String filename) {

		FileInputStream msg = null;
		try {
			
			NSKeyStore keyStore = new NSKeyStore("dns", nameserver);
			keyStore.setKeyLimit(5);
			Verifier ver = new Verifier(keyStore, "DKIM");
			ver.setleniency(true);
			msg = new FileInputStream(filename);
				
			//ver.setBadDomains(new String[] { "gmail.com" });
			ver.setMaximumSigs(3);
			
			ver.verifyMail(msg);
			System.out.println("Message Verified :-)");
			msg.close();	
			

		} catch (DkimException d) {
				
			try {msg.close(); } catch (Exception e) { };
			
			if ( d.getErrorType() == ErrorType.NOSIG) {
				// No signature, 
				System.err.println("NOSIG -- " + d.getError().getStatus());
				System.err.println(d.getError().getDescription());
				System.err.println(d.getMessage());
				d.printStackTrace();
			} 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();
		}
	}


}
