#!/bin/bash
#                                                                                       #
# SCRIPT: couch_service.sh		                                                #
# DATE:   27-Oct-2016                                                                   #
# REV:    1.0                                                                           #
# DEVELOPED BY: Parablu Systems								#
# DEVELOPER: Vaibhav K
# PURPOSE: Contains all the utility functions for couchdb Installation                  #
# PLATFORM: Ubuntu                                                                      #

PARABLU_CONFIG_SCRIPT_PATH=../config/parablu_config.sh
source $PARABLU_CONFIG_SCRIPT_PATH

#installing couchdb
function install_couchdb ()
{
	if [ ! -e /etc/couchdb ]
	then
		apt-get -y install couchdb
	fi
}

#configure couchdb
function configure_couchdb ()
{
	if [ "`grep -o '_default' /etc/couchdb/default.ini | grep 'db_fragmentation, "50%"' | wc -l`" -le 0 ]
	then
		echo '_default = [{db_fragmentation, "50%"}, {view_fragmentation, "50%"}, {from, "23:00"}, {to, "04:00"}]' >> /etc/couchdb/default.ini
	fi

	if [ "`grep -o 'parablu' /etc/couchdb/local.ini | wc -l`" -le 0 ]
	then
		echo "creating user for couch"
		echo "root=parablu" >> /etc/couchdb/local.ini
	fi
	service couchdb restart
	sleep 10
	echo "cloudname:"$CLOUD_NAME
	echo "creating couch database"	
	curl -X PUT http://root:parablu@localhost:5984/privacy_gateway_backup_$CLOUD_NAME
	curl -X PUT -d "2" http://root:parablu@localhost:5984/privacy_gateway_backup_$CLOUD_NAME/_revs_limit
	service couchdb restart
	sleep 5
}


# check whether couchdb is installed in the system
function verify_couchdb ()
{

	if [ ! -e /etc/couchdb/local.ini ] 
	then
		echo "Couchdb Installation failed. Try again after some time"
		exit 
	else
		echo "Couchdb Successfully installed"
	fi

}


function uninstall_couchdb ()
{
	service couchdb stop
	apt-get -y purge couchdb
	rm -rf /etc/couchdb
}

# external function which deploys the tomcat
function release_couchdb ()
{
	install_couchdb
	configure_couchdb
	verify_couchdb
}
