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


UBUNTU_SERVICE_SCRIPT_PATH=./ubuntu_service.sh

source $UBUNTU_SERVICE_SCRIPT_PATH

# Configure all the prerequisite components
function prerequisite_tomcat ()
{
	if  [ ! -e "/var/lib/tomcat" ] 
	then 
		add_system_users
		install_common_packages
		install_jre
	fi
}

# install tomcat from internet
function install_tomcat ()
{
	if [ ! -e "/var/lib/tomcat" ]
	then
		#download apache-tomcat directly to /var/lib/
	#	wget -O /var/lib/apache-tomcat-7.0.39.tar.gz https://archive.apache.org/dist/tomcat/tomcat-7/v7.0.39/bin/apache-tomcat-7.0.39.tar.gz 2> /dev/null
		cp ../installables/apache-tomcat-9.0.24.tar.gz /var/lib/apache-tomcat-9.0.24.tar.gz

		#unzip the .tar / remove the .tar file
		tar -xf /var/lib/apache-tomcat-9.0.24.tar.gz -C /var/lib/

		sleep 5
		# link to tomcat insteed og apache-tomcat-7.0.39
		ln -s /var/lib/apache-tomcat-9.0.24/ /var/lib/tomcat

		chmod -R 644 /var/lib/tomcat/lib/*.jar
		chmod -R 644 /var/lib/tomcat/bin/*.jar
		chmod -R 755 /var/lib/tomcat/bin/startup.sh
		chmod -R 755 /var/lib/tomcat/bin/catalina.sh
		chmod -R 755 /var/lib/tomcat/*
		hide_tomcat_version
		

	fi
}

# check whether tomcat is installed in the system
function verify_tomcat ()
{
	if  [ ! -e "/var/lib/tomcat" ] 
	then 
		echo "Tomcat Installation failed. Try again after some time"
		exit 0
	else
		echo "Tomcat installed successfully"
	fi
}

## Allocate ram  to  java
function allocate_tomcat_ram ()
{
        total_ram=$(free -m | awk '{print $2}' | head -2 | sed -n 2p)
        half_ram=`expr $total_ram / 2`
        echo "CATALINA_OPTS=\""-Dfile.encoding=UTF-8 -Xms512m -Xmx$half_ram\m -XX:PermSize=128m -XX:MaxPermSize=1024m"\"" >/var/lib/apache-tomcat-7.0.39/bin/setenv.sh
        chmod 755 /var/lib/apache-tomcat-7.0.39/bin/setenv.sh

}


function hide_tomcat_version ()
{

	mkdir -p /var/lib/tomcat/lib/org/apache/catalina/util
	cp ../installables/ServerInfo.properties /var/lib/tomcat/lib/org/apache/catalina/util


}

# external function which deploys the tomcat
function release_tomcat ()
{
	prerequisite_tomcat
	install_tomcat
	verify_tomcat
}

function uninstall_tomcat ()
{
	rm -rf /var/lib/apache-tomcat-7.0.39/
	rm -rf /var/lib/tomcat
}

