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

UBUNTU_SERVICE_SCRIPT_PATH=./ubuntu_service.sh
PARABLU_COMPONENT_SCRIPT_PATH=../config/parablu_component_config.sh
source $UBUNTU_SERVICE_SCRIPT_PATH 
source $PARABLU_COMPONENT_SCRIPT_PATH
#APACHE_LOG_DIR="$ROOT_PATH/log/apache2"
# Configure all the prerequisite components
function prerequisite_apache ()
{
	if [ ! -e /etc/apache2/apache2.conf ]
	then
		add_system_users
		install_common_packages
		install_jre
		install_rar
	fi
}

# installing apache
function install_apache ()
{
	#if [ ! -e /etc/apache2/apache2.conf ]
	if [ ! -e ../installables/apache_installed ]
	then
		#Apache2
		apt-get -y install apache2
		sleep 2
		configure_apache_cert_key

		#install openssl
                #curr_dir=`pwd`
                #cd $DEFAULT_FILE_PATH
                #tar -xf openssl-1.0.2g.tar.gz
                #cd openssl-1.0.2g/
                #./config --prefix=/usr/
                #make
                #sudo make install
                #cd $curr_dir
                sleep 2s

		#enable_mods
		apachectl -k restart
		sleep 2
		apachectl -t -D DUMP_MODULES
		a2enmod headers
		service apache2 restart
		a2enmod expires
		service apache2 restart
		a2enmod jk
		service apache2 restart
		a2enmod ssl
		service apache2 restart
		a2enmod proxy
		service apache2 restart
		a2enmod proxy_http
		service apache2 restart
		a2enmod rewrite
		service apache2 restart
		sleep 2
	
		#apache_conf files
		configure_apache
		
		#apache_sites_enabled
		apache_sites_enabled_http_conf
		apache_sites_enabled_https_conf
		configure_request_workers

		#JK-
		apt-get -y install libapache2-mod-jk
		service apache2 restart
		sleep 2
		configure_apache_tomcat
		configure_jk
		touch ../installables/apache_installed
	fi
}

#configuring apache tomcat 
function configure_apache_tomcat ()
{
	if [ "`grep -os 'worker1,worker2' /etc/apache2/tomcat.workers | wc -l`" -le 0 ]
	then
		echo "workers.tomcat_home=/var/lib/tomcat               
		workers.java_home=/usr/lib/jvm/java-6-openjdk-amd64/jre  
		worker.list=balancer
		worker.worker1.type=ajp13
		worker.worker1.host=localhost
		worker.worker1.port=9610
		worker.worker1.lbfactor=1
		worker.worker2.type=ajp13
		worker.worker2.host=localhost
		worker.worker2.port=9620
		worker.worker2.lbfactor=1
		worker.balancer.type=lb
		worker.balancer.balance_workers=worker1,worker2" >> /etc/apache2/tomcat.workers
	fi
}

function configure_jk ()
{
	sed -i 's|JkWorkersFile /etc/libapache2-mod-jk/workers.properties|JkWorkersFile /etc/apache2/tomcat.workers|' /etc/apache2/mods-enabled/jk.conf
	sed -i 's|# LogFormat|LogFormat|' /etc/apache2/mods-enabled/jk.conf

	 if [ "`grep -os 'JkLogStampFormat' /etc/apache2/mods-enabled/jk.conf | wc -l`" -le 0 ]; then
		sed -i '24iJkLogStampFormat "[%a %b %d %H:%M:%S%Y]"' /etc/apache2/mods-enabled/jk.conf
	fi
}

#configuring apache cert key
function configure_apache_cert_key ()
{	
	echo "configuring certificate for apache"
	SYS_CERT_PATH=/etc/ssl/certs/
	SYS_KEY_PATH=/etc/ssl/private/
	SYS_DER_PATH=/var/lib/parablusys/private/

	echo "file path:"$FILE_PATH
	cp $DEFAULT_FILE_PATH/$CERT_FILE $SYS_CERT_PATH
	cp $DEFAULT_FILE_PATH/$KEY_FILE  $SYS_KEY_PATH
	mkdir -p $SYS_DER_PATH
	cp $DEFAULT_FILE_PATH/$DER_FILE  $SYS_DER_PATH
	cp $DEFAULT_FILE_PATH/$KEY_FILE  $SYS_DER_PATH
	sleep 2
}

function configure_apache ()
{
	if [ "`grep -os 'localhost' /etc/apache2/apache2.conf | wc -l`" -le 0 ]
	then
		echo '# Turn on Expires and set default to 0
		ExpiresActive On
		ExpiresDefault A0

		# Set up caching on media files for 1 week 
		<FilesMatch "\.(gif|jpg|jpeg|png|swf)$"> 
			ExpiresDefault A604800
			Header append Cache-Control "public" 
		</FilesMatch>

		# Set up caching on media files for 1 year 
		<FilesMatch "\.(flv|ico|pdf|avi|mov|mp3|wmv|wav)$"> 
			ExpiresDefault A29030400
			Header append Cache-Control "public"
		</FilesMatch>

		# Set up 320 Hour caching on JS/CSS
		<FilesMatch "\.(js|css)$">
			ExpiresDefault A1152000
			Header append Cache-Control "proxy-revalidate" 
		</FilesMatch>

		<ifModule mod_deflate.c>
			<filesMatch ".(js|css)$">
			SetOutputFilter DEFLATE
			</filesMatch>
		</ifModule>
		Servername localhost' >> /etc/apache2/apache2.conf

		#echo '' >> /etc/apache2/apache2.conf
                #echo '<Location />
 #   <LimitExcept GET POST>
  #      order deny,allow
   #     deny from all
    #</LimitExcept>
#</Location>' >> /etc/apache2/apache2.conf

		####VAPT change

                if [ "$SERVER_TYPE" == "0" ] || [ "$SERVER_TYPE" == "1 2" ] || [ "$SERVER_TYPE" == "1" ] || [ "$SERVER_TYPE" == "3 1" ]; then
                        echo "$BLUVAULT_IP" |  grep -e ".com" -e ".net" -e ".in" -e ".co"
                                if [ $? -eq 0 ]; then
                                        sed -i '/Servername/d' /etc/apache2/apache2.conf
                                        sed -i "/<\/ifModule>/a Servername $BLUVAULT_IP" /etc/apache2/apache2.conf
                                fi


                fi
                if [ "$SERVER_TYPE" == "2" ]; then
                        echo "$BLUKRYPT_IP" |  grep -e ".com" -e ".net" -e ".in" -e ".co"
                        if [ $? -eq 0 ]; then
                                sed -i '/Servername/d' /etc/apache2/apache2.conf
                                sed -i "/<\/ifModule>/a Servername $BLUKRYPT_IP" /etc/apache2/apache2.conf
                        fi

                fi
                sleep 2s
		service apache2 restart
	fi
}

# configure sites enabled http conf
function apache_sites_enabled_http_conf ()
{
	SITES_PATH=/etc/apache2/sites-enabled/000-default.conf
	if [ "`grep -os 'support@parablu.com' $SITES_PATH | wc -l`" -le 0 ]
	then
		echo "" > $SITES_PATH

		echo '<VirtualHost *:80>
			DocumentRoot /var/www/
			ServerAdmin support@parablu.com
			<Directory />
				Options FollowSymLinks
				AllowOverride all
			</Directory>
			<Directory /var/www/portal>
				Options Indexes FollowSymLinks MultiViews
				AllowOverride all
				Order allow,deny    
				allow from all   
			</Directory>
			ErrorLog ${APACHE_LOG_DIR}/error.log
			LogLevel warn
			CustomLog ${APACHE_LOG_DIR}/access.log combined
			JKMountCopy On
	 	</VirtualHost>' >> $SITES_PATH
	fi
}

# configure sites enabled https conf
function apache_sites_enabled_https_conf ()
{
	SITES_PATH=/etc/apache2/sites-enabled
	
	SITES_AVA_PATH=/etc/apache2/sites-available
	ln -s $SITES_AVA_PATH/default-ssl.conf $SITES_PATH/default-ssl.conf

	echo "" > $SITES_PATH/default-ssl.conf

	echo '<IfModule mod_ssl.c>

		<VirtualHost _default_:443>
	
		Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
		Header set X-XSS-Protection "1; mode=block"
		Header set Content-Security-Policy "script-src https: '\''unsafe-inline'\'' '\''unsafe-eval'\'';"
		Header set Referrer-Policy "no-referrer"
		Header unset X-Forwarded-Host
		ServerAdmin support@parablu.com
		JKMountCopy On
		DocumentRoot /var/www
		<Directory />
			Options FollowSymLinks

			AllowOverride all
		</Directory>
		<Directory /var/www/>
			Options +FollowSymLinks -Indexes -MultiViews
			AllowOverride all
			Order allow,deny
			allow from all

		</Directory>

		<Directory /var/www/portal/>
			Options +FollowSymLinks -Indexes -MultiViews
			AllowOverride all
			Order allow,deny
			allow from all
		</Directory>

		eRRorLog ${APACHE_LOG_DIR}/error.log
		LogLevel warn
		CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined

		SSLEngine on
		SSLCertificateFile /etc/ssl/certs/ca.crt
		SSLCertificateKeyFile /etc/ssl/private/ca.key

		SSLProtocol -all +TLSv1.2
		SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256
		SSLHonorCipherOrder    on
		SSLCompression         off

		<FilesMatch "\.(cgi|shtml|phtml|php)$">
			SSLOptions +StdEnvVars
		</FilesMatch>
		<Directory /usr/lib/cgi-bin>
			SSLOptions +StdEnvVars
		</Directory>
		BrowserMatch "MSIE [2-6]" \
		nokeepalive ssl-unclean-shutdown \
		downgrade-1.0 force-response-1.0
		BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
		</VirtualHost>
		ServerSignature Off
		ServerTokens Prod
		</IfModule>' >> $SITES_PATH/default-ssl.conf
}

function configure_request_workers ()
{
        sed -i 's|MaxRequestWorkers.*|MaxRequestWorkers         255 |' /etc/apache2/mods-available/mpm_worker.conf

}

# check whether apache is installed in the system
function verify_apache ()
{
	if [ ! -e /etc/apache2/apache2.conf ] || [ "`grep -o 'support@parablu.com' /etc/apache2/sites-enabled/000-default.conf | wc -l`" -ne 1 ] || [ "`grep -o 'support@parablu.com' /etc/apache2/sites-enabled/default-ssl.conf | wc -l`" -ne 1 ]
	then 
		echo "Apache Installation failed. Try again after some time"
		exit 0
	else
		echo "Apache installed successfully"
	fi
}

function uninstall_apache ()
{
	service apache2 stop
	apt-get -y purge apache2
	apt-get -y purge libapache2-mod-jk
	SYS_CERT_PATH=/etc/ssl/certs/
	SYS_KEY_PATH=/etc/ssl/private/
	SYS_DER_PATH=/var/lib/parablusys/private/
	rm -rf $SYS_CERT_PATH/$CERT_FILE $SYS_KEY_PATH/$KEY_FILE $SYS_DER_PATH/$DER_FILE $SYS_DER_PATH/$KEY_FILE
	rm -rf /etc/apache2/
	rm -rf $LOG_PATH/apache2
        rm -rf $ARCHIVE_PATH/apache2

	rm -rf $LOGROTATEROOTPATH/parablusys
        rm -rf $LOGROTATEROOTPATH/parablusys
        rm -rf $LOGROTATEROOTPATH/parablusys/bin
	rm -rf ../installables/apache_installed
}


# external function which deploys the tomcat
function release_apache ()
{
	prerequisite_apache
	install_apache
	verify_apache
}

