#!/bin/bash

# set debug mode
#set -x

# configure logging to print line numbers
#export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'

function LOG() {
	echo $1 "  " $2;
}

function executeCommand(){
        command_txt=$1;
        exitOnFailure=$2;
        #LOG info  "Executing command: $command_txt with failure flag= $exitOnFailure";

        output=$(eval $command_txt);
        return_code=$?;
        command_not_found="Command not found";
        #LOG info "Return code: $return_code, Output: $output";
        if [ $return_code -gt 0 ]; then
                LOG info "Return Code :$return_code";
                [[ "$exitOnFailure" -eq "1" ]]&& exit 1;
        fi
        if [ "${output/$command_not_found}" != "$output" ] ; then
                LOG info "Commnad not found!!";
                LOG info "Error: $output";
                exit 1;
        fi
}

##############
#
# assumes sshpass installed (yum install sshpass
#
# assumes fuse with fabric running on localhost with a test profile created

########### aliases to preconfigure ssh and scp verbose to type options

## note can use the -r and -d (retry times and dealy to try multiple times...)

ssh2fabric="/opt/fuse/jboss-fuse-6.1.0.redhat-379/bin/client -a 8101 -h localhost -u admin -p admin -r 3 -d 10"

############################# here you are starting to interact with Fuse/Karaf

# wait for ssh server to be up, avoids "Connection reset by peer" errors
while ! $ssh2fabric "echo up" ; do sleep 1s; done;

# wait for critical components to be available before progressing with other steps
executeCommand "$ssh2fabric \"wait-for-service -t 300000 io.fabric8.api.BootstrapComplete\"" "1"

COUNTER=$1;
until [  $COUNTER -lt 0 ]; do
    executeCommand "$ssh2fabric \"fabric:profile-edit --pid some.such.pid/name=value$COUNTER test\"" "1"
    let COUNTER-=1
done

