#!/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 10-default-yama-scope 50-coredump 50-default 50-libkcapi-optmem_max; do
	CFG_FILE=lib/sysctl.d/$conf.conf
	if [ -f $CFG_FILE ]; then
	    sed -e "s,^kernel.yama.ptrace_scope,# kernel.yama.ptrace_scope,g" \
		-e "s,^fs.protected_,# fs.protected_,g" \
		-e "s,^net.ipv4.conf\.,# net.ipv4.conf.,g" \
		-e "s,^net.core.default_qdisc,# net.core.default_qdisc,g" \
		-e "s,^net.core.optmem_max,# net.core.optmem_max,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"
for i in $list; do
	/bin/systemctl enable $i.service > /dev/null 2>&1
done

# turn timers on
list="logrotate"
for i in $list; do
	/bin/systemctl enable $i.timer > /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 daily* jobs
chmod a+x /etc/cron.d/dailyjobs > /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

# 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
