package com.rusefi;

import java.io.*;

/**
 * Andrey Belomutskiy (c) 2014
 */
public class Version2Header {
    private static final String COMMAND = "svn info";
    private static final String VERSION_MARKER = "Last Changed Rev: ";
    private static final String HEADER_TAG = "SVN_VERSION";

    public static void main(String[] args) throws IOException {
        Process simulatorProcess = null;
        try {
            simulatorProcess = Runtime.getRuntime().exec(COMMAND);

            BufferedReader input =
                    new BufferedReader(new InputStreamReader(simulatorProcess.getInputStream()));

            String line;
            while ((line = input.readLine()) != null) {
                System.out.println("from " + COMMAND + ": " + line);

                if (line.startsWith(VERSION_MARKER)) {
                    String ver = line.substring(VERSION_MARKER.length());
                    System.out.println("Version [" + ver + "]");
                    int version = Integer.parseInt(ver);
                    writeFile(version);
                }
            }
        } finally {
            if (simulatorProcess != null)
                simulatorProcess.destroy();
        }
    }

    private static void writeFile(int version) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("svnversion.h"));
        bw.write("// This file was generated by Version2Header\r\n");
        bw.write("#ifndef " + HEADER_TAG + "\r\n");
        bw.write("#define " + HEADER_TAG + " " + version + "\r\n");
        bw.write("#endif\r\n");
        bw.close();
    }
}
