#!/bin/bash

function move_file() {
	[ $# -eq 2 ] || exit 1
	local src=$1 dst=$2

	chown --reference=$dst $src || exit 1 
	chmod --reference=$dst $src || exit 1 
	mv -f $src $dst
}

pushd / >/dev/null

[ ! -e etc/mtab ] && ln -s /proc/mounts etc/mtab > /dev/null 2>&1

# Convert system to shadow password files
/usr/sbin/pwconv > /dev/null 2>&1

for conf in 00-system 50-coredump 50-default; do
	CFG_FILE=lib/sysctl.d/$conf.conf
	if [ -f $CFG_FILE ]; then
	    sed -e "s,^net.bridge\.,# net.bridge.,g" \
		-e "s,^net.ipv4.conf\.,# net.ipv4.conf.,g" \
		-e "s,^kernel.core_pattern,# kernel.core_pattern,g" \
		-e "s,^kernel.core_uses_pid,# kernel.core_uses_pid,g" \
		-e "s,^kernel.sysrq,# kernel.sysrq,g" \
		$CFG_FILE > ${CFG_FILE}.$$ && \
		move_file ${CFG_FILE}.$$ $CFG_FILE > /dev/null 2>&1
	fi
done

# turn services on
list="network httpd sshd xinetd saslauthd sendmail crond firewalld"
for i in $list; do
	/bin/systemctl enable $i.service > /dev/null 2>&1
done

# turn services off
list="rpcbind"
for i in $list; do
	/bin/systemctl disable $i.service > /dev/null 2>&1
done

# disable all cron jobs
for i in hourly daily weekly monthly; do
	chmod a-x /etc/cron.${i}/* > /dev/null 2>&1
done
# enable logrotate
chmod a+x /etc/cron.daily/logrotate > /dev/null 2>&1

# Fix sshd_config
CFG_FILE=etc/ssh/sshd_config
if [ -f $CFG_FILE ]; then
    sed -e "s/^X11Forwarding yes/X11Forwarding no/" \
        $CFG_FILE > ${CFG_FILE}.$$ && \
		move_file ${CFG_FILE}.$$ $CFG_FILE > /dev/null 2>&1
fi

# Turn apache ports on
/usr/bin/firewall-offline-cmd --port 80:tcp > /dev/null 2>&1

# apache tuning
echo "# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# ServerLimit: maximum value for MaxClients for the lifetime of the server
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule prefork.c>
StartServers       1
MinSpareServers    1
MaxSpareServers    5
ServerLimit       10
MaxClients        10
MaxRequestsPerChild  4000
</IfModule>
" > etc/httpd/conf.d/mpm_prefork.conf

# saslauthd tuning
CFG_FILE=etc/sysconfig/saslauthd
if [ -f $CFG_FILE ]; then
    sed -e "s/^FLAGS=/FLAGS=\"-n 2\"/" \
        $CFG_FILE > ${CFG_FILE}.$$ && \
		move_file ${CFG_FILE}.$$ $CFG_FILE > /dev/null 2>&1
fi

rm -rf run/* > /dev/null 2>&1

# Fix docker-firewalld startup
mkdir -p etc/systemd/system/docker.service.d
echo "[Unit]
After=firewalld.service
" > etc/systemd/system/docker.service.d/firewalld.conf

popd > /dev/null
