#!/bin/sh
set -e

[ -f /etc/default/elasticsearch ] && . /etc/default/elasticsearch

startElasticsearch() {
	if [ -x "/etc/init.d/elasticsearch" ]; then
		if [ -x "`which invoke-rc.d 2>/dev/null`" ]; then
			invoke-rc.d elasticsearch start || true
		else
			/etc/init.d/elasticsearch start || true
		fi
	fi
}

case "$1" in
	configure)
	[ -z "$ES_USER" ] && ES_USER="elasticsearch"
	[ -z "$ES_GROUP" ] && ES_GROUP="elasticsearch"
	if ! getent group "$ES_GROUP" > /dev/null 2>&1 ; then
	    addgroup --system "$ES_GROUP" --quiet
	fi
	if ! id $ES_USER > /dev/null 2>&1 ; then
	    adduser --system --home /usr/share/elasticsearch --no-create-home \
		--ingroup "$ES_GROUP" --disabled-password --shell /bin/false \
		"$ES_USER"
	fi

	# Set user permissions on /var/log/elasticsearch and /var/lib/elasticsearch
	mkdir -p /var/log/elasticsearch /var/lib/elasticsearch
	chown -R $ES_USER:$ES_GROUP /var/log/elasticsearch /var/lib/elasticsearch
	chmod 755 /var/log/elasticsearch /var/lib/elasticsearch
	
	# configuration files should not be modifiable by elasticsearch user, as this can be a security issue
	chown -Rh root:root /etc/elasticsearch/*
	chmod 755 /etc/elasticsearch
	find /etc/elasticsearch -type f -exec chmod 644 {} ';'
	find /etc/elasticsearch -type d -exec chmod 755 {} ';'
	
	# if $2 is set, this is an upgrade
	if ( [ -n $2 ] && [ "$RESTART_ON_UPGRADE" = "true" ] ) ; then
		startElasticsearch
	# this is a fresh installation
	elif [ -z $2 ] ; then
        echo "### NOT starting elasticsearch by default on bootup, please execute"
        echo " sudo update-rc.d elasticsearch defaults 95 10"
        echo "### In order to start elasticsearch, execute"
        echo " sudo /etc/init.d/elasticsearch start"
	fi
	;;
esac

