/*
 * Copyright 2000-2015 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package jetbrains.buildServer.clouds.vmware.client;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Eugene Petrenko
 *         Created: 09.12.2009 21:53:37
 */
public class CPMain {
  public static void main(String[] args) throws IOException {
    //We have to omit last application classloader in order to re-load pluigns classes
    final String newAgentMainClass = CPMain.class.getName().replace("CPMain", "Main");

    try {
      final ClassLoader agentLoader = new URLClassLoader(getAgentLibraries(), null);
      Thread.currentThread().setContextClassLoader(agentLoader);
      Class<?> main = agentLoader.loadClass(newAgentMainClass);
      final Method mainMethod = main.getMethod("main", String[].class);
      mainMethod.invoke(null, new Object[]{args});
    } catch (ClassNotFoundException e) {
      System.err.println("Failed to find build agent class " + newAgentMainClass + ". " + e.getMessage());
      debug(e);
    } catch (NoSuchMethodException e) {
      System.err.println("Failed to find main method in agent class " + newAgentMainClass + ". " + e.getMessage());
      debug(e);
    } catch (IllegalAccessException e) {
      System.err.println("Failed to call main method in agent class " + newAgentMainClass + ". " + e.getMessage());
      debug(e);
    } catch (InvocationTargetException e) {
      System.err.println("main method of agent class " + newAgentMainClass + " has failed. " + e.getMessage());
      debug(e);
    }
  }

  private static URL[] getAgentLibraries() throws IOException {
    final File libFolder = new File(CPUtil.getClasspathEntry(CPMain.class), "../lib").getCanonicalFile();
    System.out.println("Loading libraries from: " + libFolder);

    final File[] files = libFolder.listFiles(new FilenameFilter() {
      public boolean accept(final File dir, final String name) {
        return name.endsWith(".jar");
      }
    });
    if (files == null || files.length == 0) {
      return new URL[0];
    }

    try {
      List<URL> urls = new ArrayList<URL>();
      for (File file : files) {
        urls.add(file.toURL());
      }
      return urls.toArray(new URL[urls.size()]);
    } catch (MalformedURLException e) {
      //
    }
    return new URL[0];
  }


  private static void debug(final Exception e) {
    e.printStackTrace();
  }
}
