/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2016. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
package com.urbancode.air.plugin.websphereliberty;
import com.urbancode.air.CommandHelper;
import groovy.xml.StreamingMarkupBuilder;
import groovy.util.slurpersupport.NoChildren;
import groovy.xml.XmlUtil;
import com.urbancode.commons.util.IO;

public class WebSphereLibertyServerXmlHelper extends AbstractWebSphereLibertyFileSystemHelper {
   def ch
   def serverDirFile
   def serverXmlFile

   public WebSphereLibertyServerXmlHelper(String wlpHome, String serverName, String wlpUserDir=null) {
       super(wlpHome, wlpUserDir);
       ch = new CommandHelper(new File("."));
       serverDirFile = getServerDirectory(serverName);
       serverXmlFile = new File(serverDirFile, "server.xml");
       if (!serverXmlFile.isFile()) {
           throw new IllegalArgumentException("server.xml file not located at location : " + serverXmlFile.absolutePath);
       }
   }

   public void installOrUpdateApplicationIntoXml(String loc, String name, String type, String context, boolean autoStart) {
      def serverXml = new XmlSlurper().parse(serverXmlFile);
      def curApp = serverXml.application.find { it.@name.text() == name };
      if (curApp != null && !(curApp instanceof NoChildren)) {
          System.out.println("Found currently installed App with name ${name}! Updating ...");
          def args = [:];
          args.location = loc;
          args.name = name;
          args.type = type;
          if (context) {
              args."context-root" = context;
          }
          args.autoStart = String.valueOf(autoStart);
          curApp.replaceNode { node ->
              application(args);
          }
      }
      else {
          System.out.println("Application not found in server.xml! Installing...");
          def args = [:];
          args.location = loc;
          args.name = name;
          args.type = type;
          if (context) {
              args."context-root" = context;
          }
          args.autoStart = String.valueOf(autoStart);
          serverXml.appendNode() {
              application(args);
          }
      }
      writeXml(serverXml);
   }

   public void uninstallApplicationFromXml(String name) {
      def serverXml = new XmlSlurper().parse(serverXmlFile);
      def curApp = serverXml.application.find { it.@name.text() == name };
      if (curApp != null && !(curApp instanceof NoChildren)) {
          System.out.println("Found currently installed application with name ${name}! Removing...");
          curApp.replaceNode() {};
          writeXml(serverXml);
      }
      else {
          System.out.println("Application named ${name} not found in server.xml!");
      }
   }

   public void appendIncludeInServerXml(String fileName) {
       File fileToInclude = new File(fileName);
       if (fileToInclude.isFile()) {
           System.out.println("Appending include of ${fileName} to server.xml.");
           System.out.println(fileToInclude.getText('UTF-8'));

           String locationValue = fileToInclude.absolutePath;
           if (locationValue.startsWith(serverDirFile.absolutePath))
               locationValue = "\${server.config.dir}/" + fileToInclude.getName();
           def serverXml = new XmlSlurper().parse(serverXmlFile);
           def args = [:];
           args.location = locationValue;
           serverXml.appendNode { node ->
               include(args);
           }
           writeXml(serverXml);
       }
       else {
           throw new RuntimeException("File named ${fileToInclude} not found!  Unable to update server.xml.");
       }
   }

   public void updateQuickStartSecurity(String user, String password, String xmlFileName) {
      def xmlFile = new File(xmlFileName);
      def serverXml = new XmlSlurper().parse(xmlFile);
      def qss = serverXml.quickStartSecurity;
      if (qss != null) {
          System.out.println("Found quickStartSecurity! Updating ...");
          def args = [:];
          args.userName = user;
          args.userPassword = password;
          qss.replaceNode { node ->
              quickStartSecurity(args);
          }
          writeXml(serverXml, xmlFile);
      }
      else {
          throw new RuntimeException("quickStartSecurity node not found in ${xmlFileName}");
      }
   }

   private void writeXml(def serverXml, xmlFile=serverXmlFile) {
       System.out.println(xmlFile.getName() + " has changed! Writing out...");
       File newServerFile = File.createTempFile("server", ".xml");
       newServerFile.deleteOnExit();
       String result = XmlUtil.serialize(new StreamingMarkupBuilder().bind { mkp.yield serverXml });
       println result; 
       newServerFile.append(result, "utf-8");
       IO.move(newServerFile, xmlFile);
       System.out.println(xmlFile.getName() + " updated!");
   }
   
}
   
