/*
 *  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 com.github.sakserv;

import com.github.sakserv.config.ConfigVars;
import com.github.sakserv.config.PropertyParser;
import com.github.sakserv.jdbc.JdbcGenerator;
import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
    
    private static PropertyParser propertyParser = new PropertyParser();

    // Logger
    private static final Logger LOG = LoggerFactory.getLogger(Main.class);
    
    private static JdbcGenerator jdbcGenerator = new JdbcGenerator();

    public static void main(String[] args) {
        
        // Arg parsing for input props file
        Options options = new Options();
        options.addOption("c", true, "configuration file");

        CommandLineParser parser = new BasicParser();
        CommandLine cmd;
        String propertyFileName = "";
        try {
            cmd = parser.parse(options, args);

            // Load the props file
            if(cmd.hasOption("c")) {
                propertyFileName = cmd.getOptionValue("c");
            } else {
                propertyFileName = ConfigVars.DEFAULT_PROPS_FILE;
            }
        } catch(ParseException e) {
            LOG.error("ERROR: Failed to parse commandline args!");
            e.printStackTrace();
        }
        LOG.info("Loading and parsing the property file: " + new File(propertyFileName).getAbsolutePath());
        propertyParser.setPropFileName(propertyFileName);
        propertyParser.parsePropsFile();
        
        // Establish the connection
        String noDbConnString = propertyParser.getProperty(ConfigVars.JDBC_CONNECTION_STRING_PREFIX_VAR) +
                propertyParser.getProperty(ConfigVars.JDBC_HOSTNAME_VAR) + ":" +
                propertyParser.getProperty(ConfigVars.JDBC_PORT_VAR);
        LOG.info("Establishing connection to: " + noDbConnString);
        Connection connection = null;
        try {
            connection = jdbcGenerator.getConnectionNoDb(
                    propertyParser.getProperty(ConfigVars.JDBC_CONNECTION_STRING_PREFIX_VAR),
                    propertyParser.getProperty(ConfigVars.JDBC_HOSTNAME_VAR),
                    propertyParser.getProperty(ConfigVars.JDBC_PORT_VAR),
                    propertyParser.getProperty(ConfigVars.JDBC_USER_VAR),
                    propertyParser.getProperty(ConfigVars.JDBC_PASSWORD_VAR)
            );
        } catch (SQLException e) {
            LOG.error("ERROR: Failed to connect to database at: " + noDbConnString +
            " using username: " + propertyParser.getProperty(ConfigVars.JDBC_USER_VAR));
            e.printStackTrace();
        }
                
        // Create the grants
        try {
            LOG.info("Running grants for user " + propertyParser.getProperty(ConfigVars.JDBC_USER_VAR) + 
                    " on " + noDbConnString);
            Statement statement = connection.createStatement();
            String sqlGrant = "GRANT ALL PRIVILEGES ON *.* TO " + 
                    "\"" + propertyParser.getProperty(ConfigVars.JDBC_USER_VAR) + "\"@" + 
                    "\"%\" IDENTIFIED BY \"" + propertyParser.getProperty(ConfigVars.JDBC_PASSWORD_VAR) + "\"";
            displayQueryDebug(sqlGrant);
            statement.executeQuery(sqlGrant);
            
            statement = connection.createStatement();
            String sqlFlushPriv = "FLUSH PRIVILEGES";
            displayQueryDebug(sqlFlushPriv);
            statement.executeQuery(sqlFlushPriv);
            
        } catch (SQLException e) {
            LOG.error("ERROR: Error applying grants for user: " + propertyParser.getProperty(ConfigVars.JDBC_USER_VAR));
            e.printStackTrace();
        }

        // Create the database
        if (!Boolean.parseBoolean(propertyParser.getProperty(ConfigVars.JDBC_SKIP_DATABASE_CREATE_VAR))) {
        try {
            LOG.info("Creating the database: " + propertyParser.getProperty(ConfigVars.JDBC_DATABASE_VAR));
            Statement statement = connection.createStatement();
            String sqlCreateDatabase = "CREATE DATABASE " + propertyParser.getProperty(ConfigVars.JDBC_DATABASE_VAR);
            displayQueryDebug(sqlCreateDatabase);
            statement.executeQuery(sqlCreateDatabase);
        } catch(SQLException e) {
            LOG.error("ERROR: Failed to create database: " +  propertyParser.getProperty(ConfigVars.JDBC_DATABASE_VAR));
            e.printStackTrace();
        }

    }
    
    private static void displayQueryDebug(String sql) {
        LOG.info("Running the following statement: " + sql);
    }
    
}

@@ -4500,38 +4500,46 @@
 AR))) %7B%0A        
+    
 try %7B%0A
+    
             LOG.
@@ -4634,32 +4634,36 @@
 ));%0A            
+    
 Statement statem
@@ -4702,32 +4702,36 @@
 ();%0A            
+ 
+   
 String sqlCreate
@@ -4824,32 +4824,36 @@
 R);%0A            
+    
 displayQueryDebu
@@ -4866,32 +4866,36 @@
 reateDatabase);%0A
+    
             stat
@@ -4941,23 +4941,28 @@
         
+  
+  
 %7D catch
+ 
 (SQLExce
@@ -4964,32 +4964,36 @@
 LException e) %7B%0A
+    
             LOG.
@@ -5036,17 +5036,16 @@
 ase: %22 +
- 
  propert
@@ -5100,32 +5100,36 @@
 ));%0A            
+    
 e.printStackTrac
@@ -5137,26 +5137,39 @@
 ();%0A        
+ 
+   %7D%0A        
 %7D
-%0A
 %0A    %7D%0A    %0A

fix if statement