package com.github.aureliano.achmed.resources;

import org.apache.log4j.Logger;

import com.github.aureliano.achmed.resources.exec.CommandFacade;
import com.github.aureliano.achmed.resources.properties.ExecProperties;
import com.github.aureliano.achmed.resources.properties.IResourceProperties;

public class ExecResource implements IResource {

	private static final Logger logger = Logger.getLogger(ExecResource.class);
	
	private ExecProperties properties;
	
	public ExecResource() {
		this.properties = new ExecProperties();
	}
	
	public ExecResource(ExecProperties properties) {
		this.properties = properties;
	}

	public void apply() {
		logger.info(" >>> Apply exec resource with command: " + this.properties.getCommand());
		
		this.properties.configureAttributes();
		int exitStatusCode = 0;
		int tries = 0;
		
		do {
			exitStatusCode = CommandFacade.executeCommand(this.properties);
			tries ++;
			
			logger.debug("Exit status code: " + exitStatusCode);
			logger.debug("Tries: " + tries);
		} while ((tries < this.properties.getTries()) && (exitStatusCode != 0));
	}
	
	public void setProperties(IResourceProperties properties) {
		this.properties = (ExecProperties) properties;
	}
	
	public IResourceProperties getProperties() {
		return this.properties;
	}

	public ResourceType type() {
		return ResourceType.EXEC;
	}
}
@@ -74,16 +74,84 @@
 ogger;%0A%0A
+import com.github.aureliano.achmed.exception.ExecResourceException;%0A
 import c
@@ -1141,16 +1141,132 @@
 != 0));%0A
+%09%09%0A%09%09if (exitStatusCode != 0) %7B%0A%09%09%09throw new ExecResourceException(this.executionErrorMessage(exitStatusCode));%0A%09%09%7D%0A
 %09%7D%0A%09%0A%09pu
@@ -1514,9 +1514,202 @@
 XEC;%0A%09%7D%0A
+%09%0A%09private String executionErrorMessage(int exitStatusCode) %7B%0A%09%09return String.format(%0A%09%09%09%22Command %5B%25s%5D exited with status code %5B%25d%5D%22,%0A%09%09%09this.properties.getCommand(),%0A%09%09%09exitStatusCode%0A%09%09);%0A%09%7D%0A
 %7D

Apply resource implementation.