package brooklyn.entity.database.postgresql;

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;

import brooklyn.entity.basic.Entities;
import brooklyn.entity.chef.ChefLiveTestSupport;
import brooklyn.entity.database.VogellaExampleAccess;
import brooklyn.entity.effector.EffectorTasks;
import brooklyn.entity.salt.SaltLiveTestSupport;
import brooklyn.entity.software.SshEffectorTasks;
import brooklyn.location.PortRange;
import brooklyn.location.basic.PortRanges;
import brooklyn.location.basic.SshMachineLocation;
import brooklyn.util.task.system.ProcessTaskWrapper;
import brooklyn.util.time.Duration;

import com.google.common.collect.ImmutableList;

/**
 * Tests Salt installation of PostgreSql.
 */
public class PostgreSqlSaltLiveTest extends SaltLiveTestSupport {

    private static final Logger log = LoggerFactory.getLogger(PostgreSqlSaltLiveTest.class);

    PostgreSqlNode psql;

    @Test(groups="Live")
    public void testPostgresStartsAndStops() throws Exception {
        psql = app.createAndManageChild(PostgreSqlSpecs.specSalt());

        app.start(ImmutableList.of(targetLocation));

        Entities.submit(psql, SshEffectorTasks.ssh("ps aux | grep [p]ostgres").requiringExitCodeZero());
        SshMachineLocation targetMachine = EffectorTasks.getSshMachine(psql);

        psql.stop();

        try {
            // if host is still contactable ensure postgres is not running
            ProcessTaskWrapper<Integer> t = Entities.submit(app, SshEffectorTasks.ssh("ps aux | grep [p]ostgres").machine(targetMachine).allowingNonZeroExitCode());
            t.getTask().blockUntilEnded(Duration.TEN_SECONDS);
            if (!t.isDone())
                Assert.fail("Task not finished yet: "+t.getTask());
            Assert.assertNotEquals(t.get(), (Integer)0, "Task ended with code "+t.get()+"; output: "+t.getStdout() );
        } catch (Exception e) {
            // host has been killed, that is fine
            log.info("Machine "+targetMachine+" destroyed on stop (expected - "+e+")");
        }
    }

    @Test(groups="Live")
    public void testPostgresScriptAndAccess() throws Exception {
        ChefLiveTestSupport.installBrooklynChefHostedConfig(app);
        PortRange randomPort = PortRanges.fromString(""+(5420+new Random().nextInt(10))+"+");
        psql = app.createAndManageChild(PostgreSqlSpecs.specChef()
                .configure(PostgreSqlNode.CREATION_SCRIPT_CONTENTS, PostgreSqlIntegrationTest.CREATION_SCRIPT)
                .configure(PostgreSqlNode.POSTGRESQL_PORT, randomPort)
            );

        app.start(ImmutableList.of(targetLocation));

        String url = psql.getAttribute(PostgreSqlNode.DB_URL);
        log.info("Trying to connect to "+psql+" at "+url);
        Assert.assertNotNull(url);
        Assert.assertTrue(url.contains("542"));

        new VogellaExampleAccess("org.postgresql.Driver", url).readModifyAndRevertDataBase();
    }

}


@@ -228,57 +228,8 @@
 es;%0A
-import brooklyn.entity.chef.ChefLiveTestSupport;%0A
 impo
@@ -2166,20 +2166,20 @@
         
-Chef
+Salt
 LiveTest
@@ -2190,43 +2190,27 @@
 ort.
-installBrooklynChefHostedConfig(app
+createLocation(mgmt
 );%0A 
@@ -2366,12 +2366,12 @@
 spec
-Chef
+Salt
 ()%0A 

Remove Chef references in PostgreSqlSaltLiveTest