001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.shell.cmds;
018
019import java.io.File;
020import java.io.InputStream;
021import java.net.URL;
022
023import org.nuxeo.shell.Argument;
024import org.nuxeo.shell.Command;
025import org.nuxeo.shell.Context;
026import org.nuxeo.shell.Shell;
027import org.nuxeo.shell.ShellException;
028import org.nuxeo.shell.fs.FileSystem;
029
030/**
031 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
032 */
033@Command(name = "install", help = "Install a SH script to launch the shell in the terminal. Available only for UNIX systems.")
034public class Install implements Runnable {
035
036    @Context
037    Shell shell;
038
039    @Argument(name = "file", required = false, index = 0, help = "the file where to install the shell script. If not used the script will be printed on stdout.")
040    protected File file;
041
042    public void run() {
043        try {
044            if (file == null) {
045                // dump on stdout
046                shell.getConsole().println(getShellScript());
047            } else {
048                FileSystem.writeFile(file, getShellScript());
049                file.setExecutable(true);
050            }
051        } catch (Exception e) {
052            throw new ShellException("Failed to install shell script", e);
053        }
054    }
055
056    public String getShellScript() throws Exception {
057        InputStream in = Install.class.getClassLoader().getResourceAsStream("run.sh");
058        String content = FileSystem.read(in);
059        URL url = Install.class.getProtectionDomain().getCodeSource().getLocation();
060        String path = new File(url.toURI()).getAbsolutePath();
061        return content.replace("%SHELL_JAR%", path);
062    }
063}