/*
 * Copyright
 *  2009 axYus - www.axyus.com
 *  2009 Christophe Marchand <christophe.marchand@axyus.com>
 * 
 * This file is part of XEMELIOS.
 * 
 * XEMELIOS 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.
 * 
 * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 */

package fr.gouv.finances.cp.xemelios.patches;

import fr.gouv.finances.cp.xemelios.updater.AbstractConfigurator;
import java.io.File;
import java.io.FileOutputStream;

/**
 *
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class Core4_0_0_21 extends AbstractConfigurator {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Core4_0_0_21.class);

    @Override
    public void run() throws Exception {
        logger.info("executing "+this.getClass().getName());
        try {
            if(System.getProperty("os.name").toLowerCase().contains("windows")) {
                logger.info("os.name contains windows");
                String allUserHome = System.getenv("ALLUSERSPROFILE");
                logger.info("ALLUSERPROFILE="+allUserHome);
                File home = new File(allUserHome);
                if(home.exists()) {
                    logger.info(allUserHome+" exists");
                    File startMenu = new File(home,"Menu Démarrer");
                    if(!startMenu.exists() || !startMenu.isDirectory()) {
                        startMenu = new File(home,"Start Menu");
                        if(!startMenu.exists() || !startMenu.isDirectory()) startMenu = null;
                    }
                    if(startMenu!=null) {
                        logger.info("startMenu exists and is "+startMenu.getAbsolutePath());
                        File programs = new File(startMenu,"Programmes");
                        if(!programs.exists() || !programs.isDirectory()) {
                            programs = new File(startMenu,"Programs");
                            if(!programs.exists() || !programs.isDirectory()) programs=null;
                        }
                        if(programs!=null) {
                            logger.info("programs exists and is "+programs.getAbsolutePath());
                            File xemelios = new File(programs,"Xemelios");
                            if(xemelios.exists() && xemelios.isDirectory()) {
                                logger.info("xemelios exists and is a Directory : "+xemelios.getAbsolutePath());
                                try {
                                    File xemeliosReader = new File(xemelios,"Xemelios Reader.lnk");
                                    if(!xemeliosReader.exists()) {
                                        logger.info("creating shortcut at "+xemeliosReader.getAbsolutePath());
                                        createShortcut(xemeliosReader);
                                    } else {
                                        logger.info(xemeliosReader.getAbsolutePath()+" exists");
                                    }
                                } catch(Throwable t) {
                                    logger.error("while newFile(xemelios,\"Xemelios Reader.lnk\")",t);
                                }
                            } else {
                                logger.warn("xemelios program folder does not exists at "+xemelios.getAbsolutePath());
                            }
                        } else {
                            logger.warn("programs dir not found in "+startMenu.getAbsolutePath()+"\n\tlooking for \"Programmes\", \"Programs\"");
                        }
                    } else {
                        logger.warn("start menu not found in "+allUserHome+"\n\tlooking for \"Menu Démarrer\", \"Start Menu\"");
                    }
                } else {
                    logger.warn(allUserHome+" does not exists");
                }
            } else {
                logger.warn("ce n'est pas un windows: "+System.getProperty("os.name"));
            }
        } catch(Exception ex) {
            logger.error("while patching",ex);
        }
        setPreviousConfigurator(new Core4_0_0_17());
    }

    private void createShortcut(File target) {
        logger.info("createShortcut("+target.getAbsolutePath()+")");
        String CRLF = System.getProperty("line.separator");
        StringBuilder sb = new StringBuilder();
        sb.append("Set oWS = WScript.CreateObject(\"WScript.Shell\")").append(CRLF);
        sb.append("sLinkFile = \"").append(target.getAbsolutePath()).append("\"").append(CRLF);
        sb.append("Set oLink = oWS.CreateShortcut(sLinkFile)").append(CRLF);
        File root = new File(new File(props.replace("${xemelios.prg}")),"root");
        File xemeliosReader = new File(root,"viewdoc.cmd");
        sb.append("oLink.TargetPath = \"").append(xemeliosReader.getAbsolutePath()).append("\"").append(CRLF);
        sb.append("oLink.Description = \"Xemelios Reader\"").append(CRLF);
        File icon = new File(root,"xemelios.ico");
        sb.append("oLink.IconLocation = \"").append(icon.getAbsolutePath()).append("\"").append(CRLF);
        sb.append("oLink.WindowStyle = \"7\"").append(CRLF);
        sb.append("oLink.WorkingDirectory = \"").append(root.getAbsolutePath()).append("\"").append(CRLF);
        sb.append("oLink.Save").append(CRLF);

        File script = new File(root,"xemelios-reader.vbs");
        try {
            FileOutputStream fos = new FileOutputStream(script);
            fos.write(sb.toString().getBytes());
            fos.flush(); fos.close();
        } catch(Exception ex) {
            logger.error("while writting script",ex);
        }
        logger.info(script.getAbsolutePath()+" written\n"+sb.toString());
        String[] cmd = {"CSCRIPT",script.getAbsolutePath()};
        logger.info("running script");
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();
            int ret = p.exitValue();
            script.delete();
            logger.info("script -> "+ret);
        } catch(Exception ex) {
            logger.error("while running script",ex);
            logger.error(script.getAbsolutePath()+" is still available");
        }
    }

}
