/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ipchanger;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.StringTokenizer;

/**
 *
 * @author katerina.dimitriou
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String sourceDir = "";
        String targetDir = "";
        String sourceIp = "";
        String targetIp = "";

        if (args.length != 4) {
            System.out.println("Wrong number of arguments");
            System.out.println("USAGE: java -jar IP_changer.jar -sdir=... -tdir=... -sip=... -tip=...");
            return;
        }

        for (int i = 0; i < args.length; i++) {
            String[] argParts = args[i].split("=");
            if (argParts.length != 2) {
                System.out.println("USAGE: java -jar IP_changer.jar -sdir=... -tdir=... -sip=... -tip=...");
                return;
            }
            if (argParts[0].equals("-sdir")) {
                sourceDir = argParts[1] + "\\";
            }
            if (argParts[0].equals("-tdir")) {
                targetDir = argParts[1] + "\\";
            }
            if (argParts[0].equals("-sip")) {
                sourceIp = argParts[1];
            }
            if (argParts[0].equals("-tip")) {
                targetIp = argParts[1];
            }
        }

        System.out.println("Source Dir: " + sourceDir);
        System.out.println("Target Dir: " + targetDir);
        System.out.println("Source Ip: " + sourceIp);
        System.out.println("Target Ip: " + targetIp);

        String[] testDirs = GetDirectories(sourceDir);
        String[] testFiles = GetFiles(sourceDir);

        System.out.println("\nDIRS");
        for (int k = 0; k < testDirs.length; k++) {
            System.out.println(testDirs[k]);
        }

//        System.out.println("\nFILES");
//        for (int l = 0; l < testFiles.length; l++) {
//            System.out.println(testFiles[l]);
//        }
        
        createMirrorForDir(sourceDir , targetDir, sourceIp, targetIp);
//        doreplace("C:/", "WSDLGenerator.java", "C:/target/", "Main", "NIANIANIANIANIA");
    }
    
    public static void createMirrorForDir(String directory, String targetDirectory, String sourceIp, String targetIp) {
        System.out.println("In dir : " + directory + "\nTarget Dir: " + targetDirectory);
        String[] testFiles = GetFiles(directory);
        String[] testDirs = GetDirectories(directory);
        
        for (int i=0; i<testFiles.length; i++) {
            if(testFiles[i].endsWith(".java")) {
//                System.out.println("FILE: " + testFiles[i]);
                doreplace(directory + testFiles[i], targetDirectory + testFiles[i], sourceIp, targetIp);
            }
        }
        
        for (int k=0; k<testDirs.length; k++) {
            if (!testDirs[k].equals("")) {
            System.out.println("DIR: " + testDirs[k]);
            boolean success = (new File(targetDirectory + testDirs[k])).mkdir();
//            System.out.println("Creating "+ targetDirectory + testDirs[k] + " : " + success);
            createMirrorForDir(directory + testDirs[k] + "\\", targetDirectory + testDirs[k] + "\\", sourceIp, targetIp);
            
            }        
        
        }
    }
    
    public static void doreplace(String File, String targetFile, String From, String To) {

        // if(args.length!=2&&args.length!=3)
        //	{
        // invalid number of arguments specified at command line
        //		System.out.println("Usage(s):\n");
        //		System.out.println("  1.  java TextRep file_to_process \"search_for_word\" \"replace_with_word\"");	
        //		System.out.println("  2.  java TextRep file_to_process file_of_words_to_search_replace");	
        //		return;
        //	}
        String args[] = {"", "", ""};
        args[0] = File;
        args[1] = From;
        args[2] = To;
        try {
            // make 32k buffer for output
            StringBuffer strOutput = new StringBuffer(32768);
            // read input file into a byte array
            byte[] pInput = ReadFile(args[0]);
            // make a backup copy
            //WriteFile(args[0]+".backup.copy",pInput);
            String strInput = new String(pInput);
            if (args.length == 3) {
                // check if words are empty
                if (args[1].equals("") || args[2].equals("")) {
                    System.out.println("Cannot process empty words");
                    return;
                }
                System.out.println("Replacing \"" + args[1] + "\" with \"" + args[2] + "\" in file: " + args[0]);
                // find all instances of args[1] and replace it with args[2]
                int nPos = 0;
                while (true) {
                    int nIndex = strInput.indexOf(args[1], nPos);
                    // if args[1] can no longer be found, then copy the rest of the input
                    if (nIndex < 0) {
                        strOutput.append(strInput.substring(nPos));
                        break;
                    } // otherwise, replace it with args[2] and continue
                    else {
                        strOutput.append(strInput.substring(nPos, nIndex));
                        strOutput.append(args[2]);
                        nPos = nIndex + args[1].length();
                    }
                }
                strInput = strOutput.toString();
            } else if (args.length == 2) {
                System.out.println("Processing file: " + args[0]);
                // create a string tokenizer with file args[1]
                StringTokenizer tokens = new StringTokenizer(new String(ReadFile(args[1])), "\r\n");
                // check to see of the tokenizer has even number of tokens
                int nCount = tokens.countTokens();
                if (nCount < 1 || nCount % 2 != 0) {
                    System.out.println("Invalid number of non-empty lines in file: " + args[1]);
                    return;
                }
                // for each pair of string tokens, replace the first one with the next one
                nCount = nCount / 2;
                for (int i = 0; i < nCount; i++) {
                    // string to search in the input
                    String strSearch = tokens.nextToken();
                    // string used to replace the previous one
                    String strReplace = tokens.nextToken();
                    // check if words are empty
                    if (strSearch.equals("") || strReplace.equals("")) {
                        System.out.println("Cannot process empty words");
                        return;
                    }
                    // replace each instance of strSearch with strReplace
                    System.out.println("Replacing \"" + strSearch + "\" with \"" + strReplace + "\"");
                    int nPos = 0;
                    while (true) {
                        int nIndex = strInput.indexOf(strSearch, nPos);
                        // if strSearch can no longer be found, then copy the rest of the input
                        if (nIndex < 0) {
                            strOutput.append(strInput.substring(nPos));
                            break;
                        } // otherwise, replace it with strReplace and continue
                        else {
                            strOutput.append(strInput.substring(nPos, nIndex));
                            strOutput.append(strReplace);
                            nPos = nIndex + strSearch.length();
                        }
                    }
                    // continue to process the next pair of string tokens
                    strInput = strOutput.toString();
                    strOutput = new StringBuffer(32768);
                }
            }
            // write the output string to file
            WriteFile(targetFile, strInput.getBytes());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    // helper function to read a file into a byte array
    static public final byte[] ReadFile(String strFile) throws IOException {
        int nSize = 32768;
        // open the input file stream
        BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(strFile), nSize);
        byte[] pBuffer = new byte[nSize];
        int nPos = 0;
        // read bytes into a buffer
        nPos += inStream.read(pBuffer, nPos, nSize - nPos);
        // while the buffer is filled, double the buffer size and read more
        while (nPos == nSize) {
            byte[] pTemp = pBuffer;
            nSize *= 2;
            pBuffer = new byte[nSize];
            System.arraycopy(pTemp, 0, pBuffer, 0, nPos);
            nPos += inStream.read(pBuffer, nPos, nSize - nPos);
        }
        // close the input stream
        inStream.close();
        if (nPos == 0) {
            return "".getBytes();
        }
        // return data read into the buffer as a byte array
        byte[] pData = new byte[nPos];
        System.arraycopy(pBuffer, 0, pData, 0, nPos);
        return pData;
    }

    // helper function to write a byte array into a file
    static public final void WriteFile(String strFile, byte[] pData) throws IOException {
        System.out.println("Writing file " + strFile);
        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(strFile), 32768);
        if (pData.length > 0) {
            outStream.write(pData, 0, pData.length);
        }
        outStream.close();
    }

    public static String[] GetDirectories(String Path) {
        String szReturn = "";
        int i;
        int iFound = 0;
        File f = new File(Path);

        String[] fileNames = f.list();
        for (i = 0; i < fileNames.length; i++) {
            File fTemp = new File(Path + fileNames[i]);
            if (fTemp.isDirectory()) {
                if (iFound == 0) {
                    szReturn = fTemp.getName();
                    iFound = 2;
                } else {
                    szReturn = szReturn + "," + fTemp.getName();
                }

            }
        }
        return stringtoArray(szReturn, ",");
    }

    public static String[] GetFiles(String Path) {
        String szReturn = "";
        int i;
        int iFound = 0;
        File f = new File(Path);

        String[] fileNames = f.list();
        for (i = 0; i < fileNames.length; i++) {
            File fTemp = new File(Path + fileNames[i]);
            if (fTemp.isDirectory() == false) {
                if (iFound == 0) {
                    szReturn = fTemp.getName();
                    iFound = 2;
                } else {
                    szReturn = szReturn + "," + fTemp.getName();
                }

            }
        }
        return stringtoArray(szReturn, ",");
    }

    public static String[] stringtoArray(String s, String sep) {
        StringBuffer buf = new StringBuffer(s);
        int arraysize = 1;
        for (int i = 0; i < buf.length(); i++) {
            if (sep.indexOf(buf.charAt(i)) != -1) {
                arraysize++;
            }
        }
        String[] elements = new String[arraysize];
        int y, z = 0;
        if (buf.toString().indexOf(sep) != -1) {
            while (buf.length() > 0) {
                if (buf.toString().indexOf(sep) != -1) {
                    y = buf.toString().indexOf(sep);
                    if (y != buf.toString().lastIndexOf(sep)) {
                        elements[z] = buf.toString().substring(0, y);
                        z++;
                        buf.delete(0, y + 1);
                    } else if (buf.toString().lastIndexOf(sep) == y) {
                        elements[z] = buf.toString().substring(0, buf.toString().indexOf(sep));
                        z++;
                        buf.delete(0, buf.toString().indexOf(sep) + 1);
                        elements[z] = buf.toString();
                        z++;
                        buf.delete(0, buf.length());
                    }
                }
            }
        } else {
            elements[0] = buf.toString();
        }
        buf = null;
        return elements;
    }
}
