#!/usr/bin/env bash
# ********* Starting configuration *********
while getopts m:s:x:h  option
do
case "${option}"
in
m) HOME_DIR=${OPTARG};;
s) SERVER_ID=${OPTARG};;
x) SKIP_SERVICE=${OPTARG};;
h)
    echo "DESCRIPTION: Install Anypoint Monitoring FileBeat"
    echo "Usage: $0 [options]"
    echo " "
    echo "options:"
    echo "-h,       show help"
    echo "-m,       set home directory - defaults to MULE_HOME"
    echo " "
    exit 0
    ;;
esac
done

if [[ -z "$HOME_DIR" || ! -d "$HOME_DIR" ]]; then
    if [[ -d "$MULE_HOME" ]]; then
        HOME_DIR=$MULE_HOME
    else
        cd $(dirname $0)
        cd ../..
        HOME_DIR=`pwd`
    fi
fi

echo "MULE_HOME is set to ${HOME_DIR}"

AM_HOME=${HOME_DIR}/am
source ${AM_HOME}/bin/tools/pid-file

installServiceAgent() {
    # Configuring filebeat as a service
    UNIT_FILE="/lib/systemd/system/am-filebeat.service"
    if [[ ! -d "$UNIT_FILE" ]]; then
        echo "Copying filebeat service configuration"
        sudo cp ${AM_HOME}/config/am-filebeat.template.service $UNIT_FILE
        sudo sed -i '' -e "s/\$muleHome\\$/${HOME_DIR//\//\\/}/g" $UNIT_FILE > /dev/null 2>&1
    fi
    # Create pid file to run as a service in sudo directory
    createPidFile true /etc/filebeat
    sudo systemctl daemon-reload
}

configureAgent() {
    echo "Configuring agent..."
    if (type -p java) || ([[ -n "$JAVA_HOME" ]] && [[ -x "$JAVA_HOME/bin/java" ]]); then
        java -jar ${AM_HOME}/lib/agent-configurator.jar ${HOME_DIR}
    else
        echo "Error pushing configuration because java is not installed"
    fi
}

if [[ -z "$SERVER_ID" ]]; then
    echo "Server ID should be provided using the -s option"
else
    rm ${AM_HOME}/config/filebeat.yml > /dev/null 2>&1
    touch ${AM_HOME}/config/server.id > /dev/null 2>&1
    echo "$SERVER_ID" > "${AM_HOME}/config/server.id"
fi

# Create pid file in home
createPidFile false ${AM_HOME}
configureAgent

if [[ -z "$SKIP_SERVICE" ]]; then
    if [[ "$OSTYPE" != "darwin"* ]]; then
        read -p "Do you want to use monitoring as a service? [Y|N] " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            installServiceAgent
        fi
    fi
else
  echo "Monitoring is not used as a service"
fi

exit 0
