/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/src/util/org/apache/slide/util/jinx/lib/Misc.java,v 1.1 2004/03/25 16:18:11 juergen Exp $
 * $Revision: 1.1 $
 * $Date: 2004/03/25 16:18:11 $
 *
 * ====================================================================
 *
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * 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 org.apache.slide.util.jinx.lib;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.slide.util.Files;
import org.apache.slide.util.IO;
import org.apache.slide.util.Strings;
import org.apache.slide.util.cli.Abort;
import org.apache.slide.util.nodeset.NodeSet;
import org.apache.slide.util.os.Platform;

public class Misc {
    public static String ifSet(Object obj, String left, String right) {
        return (obj != null)? left : right;
    }

    public static String tomcatVersion(File dir) {
        if (Files.join(dir, "conf", "Catalina").exists()) {
            return "tc5";
        } else {
            return "tc4";
        }
    }
    
    public static String join(String path, File file, String optPath) {
        String result;
        
        result = path + File.pathSeparator + file;
        if (optPath != null) {
            result = result + File.pathSeparator + optPath;
        }
        return result;
    }
    
    public static String getDate() {
        return new Date().toString();
    }
    
    public static String getHost() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (IOException e) {
            System.out.println("warning: cannot obtaining hostname: " + e.getMessage());
            return "localhost";
        }
    }
    
    public static void askDelete(File file) throws IOException {
        BufferedReader r;
        String line;
        
        if (!file.exists()) {
            return;
        }
        System.out.println();
        System.out.println("CAUTION: " + file + " already exists.");
        System.out.println();
        r = new BufferedReader(new InputStreamReader(System.in));
        do {
            System.out.println("Press return to delete or ctrl-c to abort");
            line = r.readLine();
        } while (!"".equals(line));
        System.out.println("deleting " + file);
        Files.delete(file);
    }
    
    public static void fail(String str, String msg) throws IOException {
        if (str == null) {
            throw new IOException(msg);
        }
    }
    
    public static String get(int idx, String str) {
        String[] ar;
        
        ar = Strings.split(str, " ");
        return ar[idx];
    }
    public static String ref(String prop) {
        return prop;
    }

    public static void checkPath(String pathStr) throws IOException {
        String[] path;
        int i;
        
        path = Strings.split(pathStr, File.pathSeparator);
        for (i = 0; i < path.length; i++) {
            if (!new File(path[i]).exists()) {
                throw new IOException("no such file or directory: " + path[i]);
            }
        }
    }
    
    public static String getRelative(File from, File to) throws IOException {
        return Files.getRelative(from, to, '/');
    }
    
    public static String trim( String s ) {
        return s.trim();
    }
    
    public static File globLocation(File dir, String pattern) throws Abort, IOException {
        List lst;
        NodeSet set;
        
        set = new NodeSet();
        set.include(pattern);
        lst = set.list(dir);
        switch (lst.size()) {
            case 0:
                throw new Abort("nothing matches " + dir + "/" + pattern);
            case 1:
                return (File) lst.get(0);
            default:
                throw new Abort("multiple matches for " + dir + "/" + pattern);
        }
    }
    
    public static void copyright(File base, File license) throws IOException {
        IO io;
        NodeSet set;
        Iterator iter;
        String replace;
        int count;
        int modified;
        
        io = new IO();
        replace = io.readString(license);
        set = new NodeSet();
        set.include("**/*.java");
        set.exclude("build/**/*.java");
        iter = set.list(base).iterator();
        count = 0;
        modified = 0;
        while (iter.hasNext()) {
            count++;
            if (patch(io, replace, (File) iter.next())) {
                modified++;
            }
        }
        System.out.println("modified " + modified + "/" + count + " files");
    }

    private static boolean patch(IO io, String replace, File file) throws IOException {
        final String START = "/*";
        final String END = "*/\n";
        String orig;
        int end;
        String copyright;
        String modified;

        try {
            orig = io.readString(file);
            if (orig.indexOf(START) != 0) {
                throw new IOException("start missing:" + START);
            }
            end = orig.indexOf(END);
            if (end == -1) {
                throw new IOException("end missing:" + END);
            }
            copyright = orig.substring(0, end);
            if (copyright.indexOf("The Apache Software Foundation") == -1 && copyright.indexOf("SOFTWARE AG") == -1) {
                throw new IOException("institution missing: " + copyright);
            }
            if (copyright.indexOf("Copyright") == -1) {
                throw new IOException("copyright missing: " + copyright);
            }
            modified = replace + orig.substring(end + END.length());
            if (modified.equals(orig)) {
                return false;
            } else {
                io.write(file, modified);
                return true;
            }
        } catch (IOException e) {
            throw new IOException(file.getPath() + ": " + e.getMessage());
        }
    }
    
    public static String getOsType() {
        return Platform.isWindows()? "win" : "unix";
    }
}



