
/*
 *  Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
*/
package oracle.sample.resource;

import groovy.lang.GroovyShell;
import oracle.sample.StringUtils;

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.PrintWriter;
import java.util.Date;

/**
 * <p>
 * </p>
 *
 * @author velsubra
 */
public class SSHResource {

    private String dir = null;

    public SSHResource(String dir) {
        if (dir == null || dir.trim().equals("")) {
            dir = "/customer/scratch";
        }
        if (!dir.startsWith("/")) {
            dir = "/" + dir;
        }
        this.dir = dir;
    }

    private String commandToScript(String cmd) {
        return StringUtils.commandToScript(cmd, dir);
    }


    @Produces("*/*")
    @GET
    public Response get(@QueryParam("script") String script, @QueryParam("cmd") String cmd) throws Exception {
        PrintWriter pr = new PrintWriter(System.out, true);

        pr.println("Running :" + cmd + ": from " + this.dir);
        GroovyShell engine = new GroovyShell();
        engine.getContext().setVariable("pwd", this.dir);
        try {
            boolean welcome = false;
            if (script == null) {
                if (cmd == null || cmd.trim().equals("")) {
                    welcome = true;
                }
                script = commandToScript(cmd);
            }


            pr.println("Running script:" + script);

            if (script == null) {
                script = "";
            }


            // ServletBinding binding = new ServletBinding(request, response, context);

            Object obj = engine.evaluate(script);
            if (obj == null) {
                obj = "";
            }

            if (welcome) {
                obj = "Welcome to UNIX4J ..\nCurrent time:" + new Date().toString();
            }


            pr.println("Current dir=" + engine.getContext().getVariable("pwd"));
            return Response.status(200).type(MediaType.TEXT_PLAIN_TYPE).header("GROOVY_SCRIPT_PWD", engine.getContext().getVariable("pwd").toString()).entity(obj).build();


//        } catch (CompilationFailedException sc) {
//            Object pwd = engine.getContext().getVariable("pwd");
//            if (pwd == null) {
//                pwd = this.dir;
//            }
//            return Response.status(400).type(MediaType.TEXT_PLAIN_TYPE).header("GROOVY_SCRIPT_PWD", pwd).entity(sc.getMessage()).build();

        } catch (Throwable t1) {
            t1.printStackTrace();


            return Response.status(500).type(MediaType.TEXT_PLAIN_TYPE).header("GROOVY_SCRIPT_PWD", engine.getContext().getVariable("pwd").toString()).entity(t1.getMessage()).build();
        } finally {

        }

    }
}
