#!/bin/bash

#
#  Variables: change these to match your setup.
#

RE_HOME=/opt/ruby-enterprise-1.8.7-2010.02
PP_HOME=${RE_HOME}/lib/ruby/gems/1.8/gems/passenger-2.2.15
PP_WORK=/var/lib/passenger/work

APACHE_USER=apache

###########################################################################################################
# These permissions are needed for Apache to run Phusion Passenger and for Phusion Passenger to run Ruby. #
###########################################################################################################

if [ -z ${RE_HOME} -o ! -d ${RE_HOME} ]; then
	echo Error: The path to Ruby Enterprise Edition is not a valid path: ${RE_HOME}.
	exit 1
fi

if [ -z ${PP_HOME} -o ! -d ${PP_HOME} ]; then
	echo Error: The path to Phusion Passenger is not a valid path: ${PP_HOME}.
	exit 1
fi

if [ -z ${PP_WORK} -o ! -d ${PP_WORK} ]; then
	echo Info: The path to the Phusion Passenger work directory has not been set or is invalid.
fi

#
# Base permissions.
#

chown -R root:root ${RE_HOME}
chmod -R u=rw,g=r,o=r ${RE_HOME}
chmod -R a+X ${RE_HOME}
chcon -R -u system_u -t usr_t ${RE_HOME}

#
# Libraries.
#

find -P ${RE_HOME} -type f -name "*.so*" -exec chmod a+x {} \;
find -P ${RE_HOME} -type f -name "*.so*" -exec chcon -t lib_t {} \;

find -P ${RE_HOME} -type f -name "*.a" -exec chmod a+x {} \;
find -P ${RE_HOME} -type f -name "*.a" -exec chcon -t lib_t {} \;

#
# Binaries.
#

find -P ${RE_HOME} -type d -name "bin" -exec chmod -R a+x {} \;
find -P ${RE_HOME} -type d -name "bin" -exec chcon -R -t bin_t {} \;

#
# Modules.
#

chmod a+x ${PP_HOME}/ext/apache2/ApplicationPoolServerExecutable
chcon -t bin_t ${PP_HOME}/ext/apache2/ApplicationPoolServerExecutable

chmod a+x ${PP_HOME}/ext/apache2/mod_passenger.so
chcon -t httpd_modules_t ${PP_HOME}/ext/apache2/mod_passenger.so

#
# Phusion Passenger work directory
#

if [ -n ${PP_WORK} -a -d ${PP_WORK} ]; then
	chown -R ${APACHE_USER}:${APACHE_USER} ${PP_WORK}
	chmod -R u=rwX,g=rX,o-rwx ${PP_WORK}
	chcon -R -u system_u -t httpd_tmpfs_t ${PP_WORK}
fi
