/*
 * LensKit, an open source recommender systems toolkit. Copyright 2010-2013
 * Regents of the University of Minnesota and contributors Work on LensKit has
 * been funded by the National Science Foundation under grants IIS 05-34939,
 * 08-08692, 08-12148, and 10-17697. This program is free software; you can
 * redistribute it and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software Foundation; either version
 * 2.1 of the License, or (at your option) any later version. This program is
 * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details. You
 * should have received a copy of the GNU General Public License along with this
 * program; if not, write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.grouplens.lenskit.eval.maven;
import org.grouplens.lenskit.eval.config.EvalConfig;

import static org.apache.commons.exec.CommandLine.parse;
import static org.apache.commons.io.FileUtils.copyFile;

import java.io.File;
import java.io.IOException;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;

/**
 * Run an R script for statistical analysis.
 * 
 * @author GroupLens Research <ekstrand@cs.umn.edu>
 */
@Mojo(name = "run-r",
        requiresDependencyResolution = ResolutionScope.RUNTIME,
        threadSafe = true)
public class RScriptMojo extends AbstractMojo {
    /**
     * The project. Gives access to Maven state.
     */
    @Parameter(property = "project",
            required = true,
            readonly = true)
    private MavenProject mavenProject;

    /**
     * The session. Gives access to Maven session state.
     */
    @Parameter(property = "session",
            required = true,
            readonly = true)
    private MavenSession mavenSession;

    /**
     * Name of R script.
     * 
     */
    @Parameter(property = "lenskit.analyze.script",
            defaultValue = "chart.R")
    private String analysisScript;

    /**
     * Name or path to executable Rscript program.
     * 
     */
    @Parameter(property = "rscript.executable",
            defaultValue = "Rscript")
    private String rscriptExecutable;

    /**
     * Location of output data from the eval script.
     */
    @Parameter(property = EvalConfig.ANALYSIS_DIR_PROPERTY,
	       defaultValue = ".")
    private String analysisDir;

    @Override
    public void execute() throws MojoExecutionException {
        getLog().info("The analysis directory is " + analysisDir);
        getLog().info("The analysisScript is " + analysisScript);
        getLog().info("The R executable is " + rscriptExecutable);
        
        // Copy the script file into the working directory.  We could just execute
        // it from its original location, but it will be easier for our users to 
        // have the copy from the src directory next to its results in target.
        File scriptFile = new File(analysisScript);
        File scriptCopy = new File(analysisDir, scriptFile.getName());
        try {
            if (! scriptFile.getCanonicalPath().equals(scriptCopy.getCanonicalPath())) {
                copyFile(scriptFile, scriptCopy);
            }
        } catch (IOException e1) {
            throw new MojoExecutionException("Unable to copy scriptFile " + scriptFile.getAbsolutePath()
                                             + " into working directory " + scriptCopy.getAbsolutePath());
        }

        // Generate the command line for executing R.
        final CommandLine command =
            parse(rscriptExecutable)
                .addArgument(scriptCopy.getAbsolutePath());
        getLog().debug("command: " + command);  

        // Execute the command line, in the working directory.
        final DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(new File(analysisDir));
        try {
            if (executor.execute(command) != 0) {
                throw new MojoExecutionException( "Error code returned for: " + command.toString() );
            }
        } catch (ExecuteException e) {
            throw new MojoExecutionException("Error executing command: " + command.toString());
        } catch (IOException e) {
            throw new MojoExecutionException("IO Exception while executing command: " + command.toString());
        }
     }

}

@@ -51,16 +51,19 @@
 toolkit.
+%0A *
  Copyrig
@@ -74,19 +74,16 @@
 010-2013
-%0A *
  Regents
@@ -130,16 +130,19 @@
 ributors
+%0A *
  Work on
@@ -153,19 +153,16 @@
 sKit has
-%0A *
  been fu
@@ -206,16 +206,19 @@
 on under
+%0A *
  grants 
@@ -230,19 +230,16 @@
 5-34939,
-%0A *
  08-0869
@@ -264,16 +264,22 @@
 0-17697.
+%0A *%0A *
  This pr
@@ -309,19 +309,16 @@
  you can
-%0A *
  redistr
@@ -339,16 +339,19 @@
 r modify
+%0A *
  it unde
@@ -387,19 +387,16 @@
  General
-%0A *
  Public 
@@ -405,16 +405,19 @@
 cense as
+%0A *
  publish
@@ -466,19 +466,16 @@
  version
-%0A *
  2.1 of 
@@ -477,16 +477,19 @@
 1 of the
+%0A *
  License
@@ -528,16 +528,22 @@
 version.
+%0A *%0A *
  This pr
@@ -550,19 +550,16 @@
 ogram is
-%0A *
  distrib
@@ -610,16 +610,19 @@
  WITHOUT
+%0A *
  ANY WAR
@@ -627,19 +627,16 @@
 ARRANTY;
-%0A *
  without
@@ -695,17 +695,17 @@
 NESS
+%0A *
  FOR A
-%0A *
  PAR
@@ -764,16 +764,19 @@
 for more
+%0A *
  details
@@ -780,15 +780,18 @@
 ils.
+%0A *%0A *
  You
-%0A *
  sho
@@ -863,16 +863,16 @@
 with
+%0A *
  this
-%0A *
  pro
@@ -932,16 +932,19 @@
 Inc., 51
+%0A *
  Frankli
@@ -944,19 +944,16 @@
 Franklin
-%0A *
  Street,

add missing license header