/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.parquet.version;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class VersionGenerator {

  public static void main(String[] args) throws IOException {
    File srcFile = new File(args[0] + "/org/apache/parquet/Version.java");
    srcFile = srcFile.getAbsoluteFile();
    File parent = srcFile.getParentFile();
    if (!parent.exists()) {
      if (!parent.mkdirs()) {
        throw new IOException("Couldn't mkdirs for " + parent);
      }
    }
    new VersionGenerator(srcFile).run();
  }

  private final FileWriter writer;

  public VersionGenerator(File file) throws IOException {
    this.writer = new FileWriter(file);
  }

  public void run() throws IOException {
    InputStream in = VersionGenerator.class.getResourceAsStream("/parquet-version.properties");
    if (in == null) {
      throw new IOException("/parquet-version.properties not found");
    }
    Properties props = new Properties();
    try {
      props.load(in);
    } finally {
      in.close();
    }

    add("package org.apache.parquet;\n" + "\n"
        + "/**\n"
        + " * This class is auto-generated by org.apache.parquet.version.VersionGenerator\n"
        + " * Do not manually edit!\n"
        + " */\n");

    add("public class Version {\n");

    add("  public static final String VERSION_NUMBER = \"");
    add(props.getProperty("versionNumber"));
    add("\";\n");

    add("  public static final String FULL_VERSION = \"");
    add(props.getProperty("fullVersion"));
    add("\";\n\n");

    add("  public static void main(String[] args) {\n");
    add("    System.out.println(FULL_VERSION);\n");
    add("  }\n");

    add("}\n");
    writer.close();
  }

  private void add(String s) throws IOException {
    writer.write(s);
  }
}
