#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
. $SCRIPT_DIR/common.sh "$@"


if [[ $IS_MASTER == 1 ]]; then

	echo "-- SETTING UP CEREBRO ----------------------------------------------------------"

    export ES_VERSION=6.0.0-beta2

    echo " - Creating elasticsearch user (if not exist)"
    elascticsearch_user_id=`id -u elasticsearch > /tmp/es_install_log 2>&1`
    if [[ $? != 0 ]]; then
        sudo useradd elasticsearch
    fi

    echo " - Simlinking cerebro config to /usr/local/etc/kibana"
    sudo ln -s /usr/local/lib/cerebro-0.6.5/conf /usr/local/etc/cerebro

    echo " - Simlinking Kibana binaries and scripts to /usr/local/sbin"
    sudo ln -s /usr/local/lib/cerebro-0.6.5/bin/cerebro /usr/local/sbin/cerebro

    echo " - Copying cerebro systemd file"
    sudo cp $SCRIPT_DIR/utils/cerebro.service /lib/systemd/system/
    sudo chmod 644 /lib/systemd/system/cerebro.service

    echo " - Checking Systemd file"
    if [[ `systemctl status cerebro | grep 'could not be found'` != "" ]]; then
        echo "cerebro systemd file installation failed"
        exit -12
    fi
    sudo systemctl status cerebro > /tmp/cerebro_install_log 2>&1
    if [[ $? != 0 && $? != 3 ]]; then
        echo "cerebro systemd file doesn't work as expected"
        exit -12
    fi  

    echo " - Testing systemd startup - starting Elasticsearch (required as dependency)"
    sudo systemctl start elasticsearch > /tmp/cerebro_install_log 2>&1
    fail_if_error $? "/tmp/cerebro_install_log" -1

    echo " - Testing systemd startup - starting cerebro"
    sudo systemctl start cerebro > /tmp/cerebro_install_log 2>&1
    fail_if_error $? "/tmp/cerebro_install_log" -1

    echo " - Testing systemd startup - Checking startup"
    sleep 8
    sudo systemctl status cerebro > /tmp/cerebro_install_log 2>&1
    fail_if_error $? "/tmp/cerebro_install_log" -1

    echo " - Testing systemd startup - stopping cerebro"
    sudo systemctl stop cerebro > /tmp/cerebro_install_log 2>&1
    fail_if_error $? "/tmp/cerebro_install_log" -1

    echo " - Enabling cerebro on startup"
    sudo systemctl enable cerebro > /tmp/cerebro_install_log 2>&1
    fail_if_error $? "/tmp/cerebro_install_log" -1

fi


#Access on http://localhost:9000




