/*
 Licensed to Diennea S.r.l. under one
 or more contributor license agreements. See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership. Diennea S.r.l. 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 herddb.server;

import herddb.client.ClientConfiguration;
import herddb.client.HDBClient;
import herddb.client.HDBConnection;
import herddb.model.TableSpace;
import java.io.File;
import java.io.FileWriter;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import org.apache.hadoop.minikdc.MiniKdc;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

/**
 * Demonstates the usage of the update "newvalue" facility to implement atomic-counters
 *
 * @author enrico.olivelli
 */
public class JAASKerberosTest {

    private MiniKdc kdc;
    private Properties conf;

    @Rule
    public TemporaryFolder kdcDir = new TemporaryFolder();

    @Rule
    public TemporaryFolder workDir = new TemporaryFolder();

    @Before
    public void startMiniKdc() throws Exception {

        createMiniKdcConf();
        kdc = new MiniKdc(conf, kdcDir.getRoot());
        kdc.start();

        String localhostName = "localhost.localdomain";
        String principalServerNoRealm = "herddb/" + localhostName;
        String principalServer = "herddb/" + localhostName + "@" + kdc.getRealm();
        String principalClientNoRealm = "herddbclient/" + localhostName;
        String principalClient = principalClientNoRealm+"@"+kdc.getRealm();
        
        System.out.println("adding principal: " + principalServerNoRealm);
        System.out.println("adding principal: " + principalClientNoRealm);

        File keytabClient = new File(workDir.getRoot(), "herddbclient.keytab");
        kdc.createPrincipal(keytabClient, principalClientNoRealm);
        
        File keytabServer = new File(workDir.getRoot(), "herddbserver.keytab");
        kdc.createPrincipal(keytabServer, principalServerNoRealm);

        File jaas_file = new File(workDir.getRoot(), "jaas.conf");
        try (FileWriter writer = new FileWriter(jaas_file)) {
            writer.write("\n"
                + "HerdDBServer {\n"
                + "  com.sun.security.auth.module.Krb5LoginModule required debug=true\n"
                + "  useKeyTab=true\n"
                + "  keyTab=\"" + keytabServer.getAbsolutePath() + "\n"
                + "  storeKey=true\n"
                + "  useTicketCache=false\n"
                + "  principal=\"" + principalServer + "\";\n"
                + "};\n"
                + "\n"
                + "\n"
                + "\n"
                + "HerdDBClient {\n"
                + "  com.sun.security.auth.module.Krb5LoginModule required debug=true\n"
                + "  useKeyTab=true\n"
                + "  keyTab=\"" + keytabClient.getAbsolutePath() + "\n"
                + "  storeKey=true\n"
                + "  useTicketCache=false\n"
                + "  principal=\"" + principalClient + "\";\n"
                + "};\n"
            );

        }

        File krb5file = new File(workDir.getRoot(), "krb5.conf");
        try (FileWriter writer = new FileWriter(krb5file)) {
            writer.write("[libdefaults]\n"
                + " default_realm = " + kdc.getRealm() + "\n"
                + "\n"
                + "\n"
                + "[realms]\n"
                + " " + kdc.getRealm() + "  = {\n"
                + "  kdc = " + kdc.getHost() + ":" + kdc.getPort() + "\n"
                + " }"
            );

        }

        System.setProperty("java.security.auth.login.config", jaas_file.getAbsolutePath());
        System.setProperty("java.security.krb5.conf", krb5file.getAbsolutePath());        

    }

    /**
     *
     * /**
     * Create a Kdc configuration
     */
    public void createMiniKdcConf() {
        conf = MiniKdc.createConf();
    }

    @After
    public void stopMiniKdc() {
        System.clearProperty("java.security.auth.login.config");
        System.clearProperty("java.security.krb5.conf");
        if (kdc != null) {
            kdc.stop();
        }
    }

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void test() throws Exception {
        try (Server server = new Server(new ServerConfiguration(folder.newFolder().toPath()))) {
            server.start();
            try (HDBClient client = new HDBClient(new ClientConfiguration(folder.newFolder().toPath()));
                HDBConnection connection = client.openConnection()) {
                client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));

                long resultCreateTable = connection.executeUpdate(TableSpace.DEFAULT,
                    "CREATE TABLE mytable (id string primary key, n1 long, n2 integer)", 0, Collections.emptyList()).updateCount;
                Assert.assertEquals(1, resultCreateTable);

                Assert.assertEquals(1, connection.executeUpdate(TableSpace.DEFAULT, "INSERT INTO mytable (id,n1,n2) values(?,?,?)", 0, Arrays.asList("test_0", 1, 2)).updateCount);
                Map<String, Object> newValue = connection.executeUpdate(TableSpace.DEFAULT, "UPDATE mytable set n1= n1+1 where id=?", 0, Arrays.asList("test_0")).newvalue;
                assertEquals(Long.valueOf(2), newValue.get("n1"));

            }
        } finally {
            System.clearProperty("java.security.auth.login.config");
        }
    }
}

@@ -969,37 +969,8 @@
 er;%0A
-import java.net.InetAddress;%0A
 impo
@@ -1117,71 +1117,8 @@
 dc;%0A
-import org.apache.log4j.Level;%0Aimport org.apache.log4j.Logger;%0A
 impo
@@ -1746,28 +1746,36 @@
        c
-reate
+onf = 
 MiniKdc
+.create
 Conf();%0A
@@ -2185,13 +2185,17 @@
 ealm
-+%22@%22+
+ + %22@%22 + 
 kdc.
@@ -2206,24 +2206,16 @@
 ealm();%0A
-        
 %0A       
@@ -2505,24 +2505,16 @@
 Realm);%0A
-        
 %0A       
@@ -4387,167 +4387,9 @@
 ());
-        %0A%0A    %7D%0A%0A    /**%0A     *%0A     * /**%0A     * Create a Kdc configuration%0A     */%0A    public void createMiniKdcConf() %7B%0A        conf = MiniKdc.createConf();
+%0A
 %0A   
@@ -4759,40 +4759,43 @@
     
-try (
 Server
- server = new Server(
+Configuration serverConfig = 
 new 
@@ -4842,16 +4842,156 @@
 oPath())
+;%0A        serverConfig.set(ServerConfiguration.PROPERTY_HOST, %22localhost.localdomain%22);%0A        try (Server server = new Server(serverConfig
 )) %7B%0A   

fix test on jenkins