package com.dbxml.db.server;

import com.dbxml.db.client.tools.CommandLine;
import com.dbxml.db.client.xmlrpc.dbXMLClientImpl;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;

public final class ServerBootstrap {
   public static void main(final String[] args) {
      PrintStream psOut = System.out;
      PrintStream psErr = System.err;

      psOut.println("Starting Bootstrap Server");

      final Map serverMap = new HashMap();

      try {
         Thread thread = new Thread() {
            public void run() {
               // Start The Skeletal Server
               serverMap.put("SERVER", new Server("install/create-db.xml"));
            }
         };
         thread.start();

         Server server = null;
         do {
            server = (Server)serverMap.get("SERVER");
            if ( server == null )
               Thread.sleep(100);
         }
         while ( server == null || !server.isRunning() );

         psOut.println("Running Bootstrap Script");

         // Execute The Bootstrap Script
         CommandLine cl = new CommandLine();
         cl.setClient(new dbXMLClientImpl());

         cl.setProperty(CommandLine.TOTALS, Boolean.FALSE);
         cl.setProperty(CommandLine.DURATIONS, Boolean.FALSE);
         cl.setProperty(CommandLine.CONFIRM, Boolean.FALSE);
         cl.setProperty(CommandLine.INTERACTIVE, Boolean.FALSE);

         cl.setWriter(new OutputStreamWriter(psOut, "UTF8"));
         cl.setErrorWriter(new OutputStreamWriter(psErr, "UTF8"));

         FileInputStream fis = new FileInputStream("install/create-db.dbxml");
         BufferedInputStream bis = new BufferedInputStream(fis, 4096);
         InputStreamReader isr = new InputStreamReader(bis, "UTF8");
         cl.setReader(isr);
         cl.process();

         psOut.println("Bootstrap Complete");
         server.shutDown(0);
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
         System.exit(1);
      }
   }
}
