// Copyright (c) Trend Micro Inc. 2004-2012, All Rights Reserved

package com.trendmicro.webserviceclient.samples;

import java.net.URL;

import com.trendmicro.webserviceclient.generated.*;
import com.trendmicro.webserviceclient.utils.ClientUtils;

/*
 * AssignDpiRule: This sample application is designed demonstrate how to correctly retrieve
 * a Deep Packet Inspection (DPI) Rule from the Deep Security Manager WebService and assign it
 * to a Security Profile.
 */
public class AssignDpiRule extends ClientUtils {
	public static int arg_count = 5;
	public static String arg_usage =
		" <webservice url> <username> <password> <security profile id/name> <dpi rule id/name>\n" +
		"This sample application can be used to assign DPI Rules to a Security Profile\n" +
		"by ID or Name.\n";
	public static int arg_endpoint = 0;
	public static int arg_user = 1;
	public static int arg_pass = 2;
	public static int arg_security_profile = 3;
	public static int arg_dpi_rule = 4;

	public static String sid = null;

	public AssignDpiRule(String app_name, String[] args) throws Exception {
		super(app_name, arg_count, arg_usage, args);
	}

	public void doAssignRule() throws Exception {
		String endpoint = this.getArg(arg_endpoint);
		String user = this.getArg(arg_user);
		String pass = this.getArg(arg_pass);
		String securityprofileidentifier = this.getArg(arg_security_profile);
		String dpiruleidentifier = this.getArg(arg_dpi_rule);

		_ManagerService = _Service.getManager(new URL(endpoint));
		try {
            /*
             * It is recommended that during initalization or start up, a version test of the
             * Web Service API be performed to ensure that Web Service API client implementations
             * built against a mis-matched version of the Deep Security Manager Web Service end
             * point does not unexpectedly break the client application.
             */
            this.log("Manager Web Service API Version: " + _ManagerService.getApiVersion());

            /*
             * When making any manager service call, such as attempting to authenticate,
             * ensure the Exception is caught. The resulting Exception message will contain
             * an explaination of any failures.
             */
			this.log("Attempting to authenticate to Manager WebService...");
			sid = _ManagerService.authenticate(user, pass);
			this.log("Authentication successful.");
			this.log("Authentication session ID string recieved: " + sid);

			this.log("Event retrieval parameters:");

			DPIRuleTransport dpirule;
			if(this.testForId(dpiruleidentifier)) {
				this.log(" - Retrieving DPI Rule by ID: " + dpiruleidentifier);
				dpirule = _ManagerService.DPIRuleRetrieve(Integer.parseInt(dpiruleidentifier), sid);
			} else {

				this.log(" - Retrieving DPI Rule by Name: " + dpiruleidentifier);
				dpirule = _ManagerService.DPIRuleRetrieveByName(dpiruleidentifier, sid);
			}
			if(dpirule == null) {
				throw new Exception("DPI Rule could not be found.");
			}

			SecurityProfileTransport securityProfile;
			if(this.testForId(securityprofileidentifier)) {
				this.log(" - Retrieving Security Profile by ID: " + securityprofileidentifier);
				securityProfile = _ManagerService.securityProfileRetrieve(Integer.parseInt(securityprofileidentifier), sid);
			} else {
				this.log(" - Retrieving Security Profile by Name: " + securityprofileidentifier);
				securityProfile = _ManagerService.securityProfileRetrieveByName(securityprofileidentifier, sid);
			}
			if(securityProfile == null) {
				throw new Exception("Security Profile could not be found.");
			}
			this.log("");
			this.log("Assigning DPI Rule to Security Profile...");
			int[] dpiRuleIds = securityProfile.getDPIRuleIDs();
			for(int dpiRuleId : dpiRuleIds) {
				if(dpiRuleId == dpirule.getID()) {
					throw new Exception("DPI Rule: " + dpirule.getName() +
							" already assigned to Security Profile:" +
							securityProfile.getName() + ".");
				}
			}
			int[] newDpiRuleIds = this.add(dpiRuleIds, dpirule.getID());
			securityProfile.setDPIRuleIDs(newDpiRuleIds);

			this.log("Saving modified Security Profile...");
			SecurityProfileTransport updateSecurityProfile =
				_ManagerService.securityProfileSave(securityProfile, sid);
			this.log("Modified Security Profile: " + updateSecurityProfile.getName() + " saved.");
		} catch(ManagerException em) {
			/*
			 * Any manager service call failures will be explained in the
			 * ManagerException fault string property.
			 */
			this.log(em.getFaultString());
		} catch(Exception e) {
			this.log("Error: " + e.getMessage());
		} finally {
			/*
			 * Always attempt to end the manager service session.
			 */
			if (sid != null)
			{
				this.log("");
				this.log("Ending session...");
				_ManagerService.endSession(sid);
				this.log("End session successful.");
			}
		}
	}

   /**
    * The main entry point.
    */
	public static void main(String[] args) throws Exception {
		AssignDpiRule client = new AssignDpiRule("AssignDpiRule", args);
		if(!client.validateArgs()) {
			client.printUsage("Invalid number of arguments found.");
			return;
		}
		client.doAssignRule();
	}
}
