#!/bin/bash
set -x
uid=`id`
uid=`echo $uid | cut -d")" -f1 | cut -d "(" -f2`
FUSE_HOME="/home/quicklab/fuse-karaf-7.10.0.fuse-7_10_0-00011-redhat-00001"
BACKUP_DIR="/home/quicklab"
statusCheck(){
        if [ $? != "0" ];then
                echo "[ERROR] :: Command Failed : Exiting now"
                exit 1
        fi
}

bundleStatus(){
        set -x
        echo "[INFO] :: In Bundlestatus Method"
        echo "[INFO] :: Bundle Status : `date`" > $BACKUP_DIR/bundleStatus.log

        cd $FUSE_HOME/bin
        ( ./client -u admin -p admin "osgi:list" >> $BACKUP_DIR/bundleStatus.log 2>&1 )
        echo "Going to read bundle status logs"
        cat $BACKUP_DIR/bundleStatus.log
        echo "[INFO] :: Deployed bundles"
        cd $FUSE_HOME/deploy/ && JAR_LIST=*.jar

        for BUNDLE in $JAR_LIST;
        do
                BUNDLE_NAME=`echo "$BUNDLE" | cut -f 1 -d '.'`
                BUNDLE_STATUS=`cat $BACKUP_DIR/bundleStatus.log | grep -i ${BUNDLE_NAME} | awk '{print $3}'`
                if [ "$BUNDLE_NAME" = "cms-sftp" ]; then
                        echo "Ignoring cms-sftp for bundle Status : $BUNDLE_STATUS"
                else
                        BUNDLE_STATUS=${BUNDLE_STATUS/[}
                        echo "[INFO] :: $BUNDLE_NAME : $BUNDLE_STATUS"

                        if [ ! "$BUNDLE_STATUS" = "Active" ];then
                                echo "[ERROR] :: Deployment failed : ${BUNDLE_NAME}"
                                exit 1;
                        fi
                fi
        done
}

jasyptTest(){
        set -x
        cd /home/quicklab/fuse-karaf-7.10.0.fuse-7_10_0-00011-redhat-00001/bin
        INSTALL_FLAG=`(./client -u admin -p admin "features:list" | grep -i 'jasypt-encryption' | grep -i 'Uninstalled' | wc -l)`
        echo "[INFO] :: jasypt-encryption install : $INSTALL_FLAG"
        if [ $INSTALL_FLAG = 1 ];then
                echo "Module not installed - jasypt-encryption. Going to install"
                INSTALL_FLAG=`(./client -u admin -p admin "features:list" | grep -i 'jasypt-encryption' | grep -i 'Uninstalled' | wc -l)`
                if [ $INSTALL_FLAG = 0 ];then
                        echo "[INFO] :: jasypt-encryption install : Successful"
                else
                        echo "[ERROR] :: jasypt-encryption install : Failed"
                        exit 1
                fi
        fi
}

#----------------------------------------------------- Execution Point -------------------------
#exit 1
jasyptTest
bundleStatus
#if [ $fcName = "jasyptValidation" ]; then
#        jasyptTest
#fi
#if [ $fcName = "bundleValidation" ]; then
#        bundleStatus
#fi
