/*
 * Filename: Installer.java
 *
 * Author: Joe Wang
 *
 * Copyright (c) 2003-2005 
 * The Trustees of Columbia University in the City of New York
 * Columbia University Information Technology
 *
 * This file is part of NINJa.
 *
 * NINJa is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * NINJa 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 NINJa; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Created on April 22, 2003, 12:40 PM
 */

package edu.columbia.print.ninja.prix;

import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.util.prefs.*;
import javax.jnlp.*;

/**
 *
 * @author  joe
 */
public class Installer {
    
    public Installer() {
    }
    
    public static void deleteAll(File file) {
        if(file.isDirectory()) {
            File[] files = file.listFiles();
            for(int i=files.length-1; i>=0; i--) deleteAll(files[i]);
        }
        file.delete();
    }

    public static void install(ExtensionInstallerService extService) throws Exception {
        System.out.println("install");
        ClassLoader cl = new Installer().getClass().getClassLoader();
        File dir = new File(extService.getInstallPath());
        Preferences prefs = Preferences.userRoot().node("edu/columbia/print/ninja/prix");
        String previousInstall = prefs.get("installDir", null);
        if(previousInstall!=null) {
            System.out.println("remove old install at: "+previousInstall);
            deleteAll(new File(previousInstall));
        }
        prefs.put("installDir", dir.getAbsolutePath());
        prefs.flush();
        byte[] buffer = new byte[4096];
        File file = new File(dir, "install.zip");
        FileOutputStream fos = new FileOutputStream(file);
        InputStream is = cl.getResourceAsStream("install.zip");
        for(;;) {
            int count = is.read(buffer);
            if(count<0) break;
            fos.write(buffer, 0, count);
        }
        //extract the jar entries
        ZipFile jar = new ZipFile(file);
        String sep = System.getProperty("file.separator");
        extService.setHeading("Extracting application");
        int i = 0;
        for(Enumeration enum=jar.entries(); enum.hasMoreElements(); i++) {
            ZipEntry entry = (ZipEntry )enum.nextElement();
            String entryName = entry.getName().replace('/', sep.charAt(0));
            File outFile = new File(dir, entryName);
            extService.setStatus("extract: "+entry.getName());
            System.out.println("extract: "+outFile.getAbsolutePath());
            extService.updateProgress(100*i/jar.size());
            if(entry.isDirectory()) {
                outFile.mkdirs();
                continue;
            }
            FileOutputStream zipFile = new FileOutputStream(outFile);
            InputStream zipIS = jar.getInputStream(entry);
            for(;;) {
                int count = zipIS.read(buffer);
                if(count<0) break;
                zipFile.write(buffer, 0, count);
            }
        }
        
        extService.setHeading("installation complete");
        extService.updateProgress(100);
        extService.setStatus("");
    }
    
    public static void uninstall(ExtensionInstallerService extService) throws Exception {
        System.out.println("uninstall:"+extService.getInstallPath());
    }
    
    public static void main(String[] args) {
        ExtensionInstallerService extService = null;
        try {
            extService = (ExtensionInstallerService )ServiceManager.lookup("javax.jnlp.ExtensionInstallerService");
            if("install".equals(args[0])) install(extService);
            else if("uninstall".equals(args[0])) uninstall(extService);
            else System.out.println("unknown arg: "+args[0]);
            extService.installSucceeded(false);
        }
        catch(Exception e) {
            e.printStackTrace();
            if(extService!=null) {
                extService.setHeading("fail "+e);
                try {Thread.sleep(30000);}
                catch(Exception ex) {}
                extService.installFailed();
            }
            return;
        }
    }
}
