#!/bin/bash
INSTALL_ROOT="/opt"
INSTALL_FOLDER="$INSTALL_ROOT/elasticsearch"
echo "Installing OpenJDK 1.7.0 ..."
sudo yum install -y java-1.7.0-openjdk
echo "[Installing ElasticSearch...]"
cd ~
echo "Downloading ElasticSearch..."
wget -c https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.7.tar.gz -O elasticsearch.tar.gz
echo "Extracting ElasticSearch..."
tar -xf elasticsearch.tar.gz
sudo mkdir -p $INSTALL_FOLDER
sudo cp -Rf elasticsearch-*/* $INSTALL_FOLDER
sudo rm -rf elasticsearch-*
echo "Installing ElasticSearch service wrapper..."
wget -c https://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master -O servicewrapper_elasticsearch.tar.gz
tar -xf servicewrapper_elasticsearch.tar.gz
sudo mv *-servicewrapper-*/service $INSTALL_FOLDER/bin/
rm -Rf *-servicewrapper-*
echo "Adding ElasticSearch user and group..."
sudo useradd elasticsearch -d $INSTALL_FOLDER -M
sudo passwd -l elasticsearch
echo "Creating neccessary folders..."
mkdir -p /home/elasticsearch/data
mkdir -p /home/elasticsearch/tmp
mkdir -p /home/elasticsearch/log
sudo chown -R elasticsearch:elasticsearch $INSTALL_FOLDER*
sudo chown -R elasticsearch:elasticsearch /home/elasticsearch
echo "Modifying init script configuration ..."
sudo sed -i -e "s|^set.default.ES_HOME.*|set.default.ES_HOME=$INSTALL_FOLDER|" $INSTALL_FOLDER/bin/service/elasticsearch.conf
sudo sed -i -e "s|^set.default.ES_HEAP_SIZE.*|set.default.ES_HEAP_SIZE=1024|" $INSTALL_FOLDER/bin/service/elasticsearch.conf
sudo sed -i -e "s|^#RUN_AS_USER=.*|RUN_AS_USER=elasticsearch|" $INSTALL_FOLDER/bin/service/elasticsearch
echo "Installing init script of ElasticSearch..."
sudo $INSTALL_FOLDER/bin/service/elasticsearch install
echo "Modifying ElasticSearch configuration..."
sudo sed -i -e "s|^# cluster.name.*|cluster.name: anphabe|" $INSTALL_FOLDER/config/elasticsearch.yml
sudo sed -i -e "s|^# path.data: path/to/data\s*|path.data: /home/elasticsearch/data|" $INSTALL_FOLDER/config/elasticsearch.yml
sudo sed -i -e "s|^# path.work.*|path.work: /home/elasticsearch/tmp|" $INSTALL_FOLDER/config/elasticsearch.yml
sudo sed -i -e "s|^# path.logs.*|path.logs: /home/elasticsearch/log|" $INSTALL_FOLDER/config/elasticsearch.yml
sudo sed -i -e "s|^# bootstrap.mlockall.*|bootstrap.mlockall: true|" $INSTALL_FOLDER/config/elasticsearch.yml
echo "Starting ElasticSearch..."
sudo service elasticsearch start
echo "Remove downloaded files..."
rm elasticsearch.tar.gz
rm servicewrapper_elasticsearch.tar.gz
echo "Install additional plugins..."
sudo $INSTALL_FOLDER/bin/plugin -install OlegKunitsyn/elasticsearch-browser
sudo $INSTALL_FOLDER/bin/plugin -install polyfractal/elasticsearch-inquisitor
sudo $INSTALL_FOLDER/bin/plugin -install mobz/elasticsearch-head