#!/bin/sh
chown=$(which chown)
chmod=$(which chmod)
cp=$(which cp)
mv=$(which mv)
rm=$(which rm)
cmp=$(which cmp)
sed=$(which sed)
php=$(which php)
grep=$(which grep)
head=$(which head)
cut=$(which cut)
PRIV_PASS=$($grep "PRIV_PASS=" /usr/sbin/svctool|$head -1|$cut -d= -f2|$sed 's{"{{g')

create_roundcube_php_config()
{
echo "<?php"
echo ""
echo "\$config = array();"
echo "\$config['db_dsnw'] = 'mysql://roundcube:subscribed@localhost/RoundCube_db';"
echo "\$config['default_host'] = 'ssl://localhost';"
echo "\$config['default_port'] = 993;"
echo "\$config['imap_auth_type'] = 'LOGIN';"
echo "\$config['imap_conn_options'] = array("
echo " 'ssl'         => array("
echo "    'verify_peer'       => false,"
echo "    'verify_peer_name'  => false,"
echo " ),"
echo ");"
echo "\$config['smtp_server'] = 'tls://localhost';"
echo "\$config['smtp_port'] = 587;"
echo "\$config['smtp_user'] = '%u';"
echo "\$config['smtp_pass'] = '%p';"
echo "\$config['smtp_auth_type'] = 'PLAIN';"
echo "\$config['smtp_conn_options'] = array("
echo "  'ssl'         => array("
echo "    'verify_peer'       => false,"
echo "    'verify_peer_name'  => false,"
echo "  ),"
echo ");"
echo "\$config['force_https'] = false;"
echo "// THIS OPTION WILL ALLOW THE INSTALLER TO RUN AND CAN EXPOSE SENSITIVE CONFIG DATA."
echo "// ONLY ENABLE IT IF YOU'RE REALLY SURE WHAT YOU'RE DOING!"
echo "\$config['enable_installer'] = false;"
echo "\$config['support_url'] = 'https://sourceforge.net/p/indimail/support-requests';"
echo "\$config['product_name'] = 'IndiMail';"
echo "\$config['useragent'] = 'IndiMail Webmail/'.RCUBE_VERSION;"
deskey=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9-_#&!*%?' | fold -w 24 | head -n 1)
echo "\$config['des_key'] = '$deskey';"
echo "\$config['language'] = 'en_US';"
echo "\$config['enable_spellcheck'] = false;"
echo "\$config['mail_pagesize'] = 50;"
echo "\$config['draft_autosave'] = 300;"
echo "\$config['mime_param_folding'] = 0;"
echo "\$config['mdn_requests'] = 2;"
echo "\$config['plugins'] = array("
echo "    'archive',"
echo "    'zipdownload',"
echo "    'sauserprefs',"
echo "    'markasjunk2',"
echo "    'iwebadmin',"
echo ");"
echo "\$config['skin'] = 'elastic';"
}

create_roundcube_httpd_conf()
{

echo "#"
echo "# Round Cube Webmail is a browser-based multilingual IMAP client"
echo "#"
echo ""
echo "Alias /indimail /usr/share/roundcubemail"
echo ""
echo "# Define who can access the Webmail"
echo "# You can enlarge permissions once configured"
echo ""
echo "<Directory /usr/share/roundcubemail/>"
echo "    <IfModule mod_authz_core.c>"
echo "        # Apache 2.4"
echo "        Require ip 127.0.0.1"
echo "        Require all granted"
echo "        Require local"
echo "    </IfModule>"
echo "    <IfModule !mod_authz_core.c>"
echo "        # Apache 2.2"
echo "        Order Deny,Allow"
echo "        Deny from all"
echo "        Allow from 127.0.0.1"
echo "        Allow from ::1"
echo "    </IfModule>"
echo "</Directory>"
echo ""
echo "# Define who can access the installer"
echo "# keep this secured once configured"
echo ""
echo "<Directory /usr/share/roundcubemail/installer/>"
echo "    <IfModule mod_authz_core.c>"
echo "        # Apache 2.4"
echo "        Require ip 127.0.0.1"
echo "        Require all granted"
echo "        Require local"
echo "    </IfModule>"
echo "    <IfModule !mod_authz_core.c>"
echo "        # Apache 2.2"
echo "        Order Deny,Allow"
echo "        Deny from all"
echo "        Allow from 127.0.0.1"
echo "        Allow from ::1"
echo "    </IfModule>"
echo "</Directory>"
echo ""
echo "# Those directories should not be viewed by Web clients."
echo "<Directory /usr/share/roundcubemail/bin/>"
echo "    Order Allow,Deny"
echo "    Deny from all"
echo "</Directory>"
echo "<Directory /usr/share/roundcubemail/plugins/enigma/home/>"
echo "    Order Allow,Deny"
echo "    Deny from all"
echo "</Directory>"
}

create_roundcube_centos_httpd_conf()
{
echo "#"
echo "# Round Cube Webmail is a browser-based multilingual IMAP client"
echo "#"
echo ""
echo "Alias /indimail /usr/share/roundcubemail"
echo ""
echo "# Define who can access the Webmail"
echo "# You can enlarge permissions once configured"
echo ""
echo "<Directory /usr/share/roundcubemail>"
echo "    Options -Indexes"
echo "    AllowOverride All"
echo "    Require all granted"
echo "</Directory>"
echo ""
echo "# Define who can access the installer"
echo "# keep this secured once configured"
echo ""
echo "<Directory /usr/share/roundcubemail/installer/>"
echo "    Require all granted"
echo "</Directory>"
echo ""
echo "<Directory /usr/share/roundcubemail/config>"
echo "    Order Deny,Allow"
echo "    Deny from All"
echo "</Directory>"
echo ""
echo "<Directory /usr/share/roundcubemail/temp>"
echo "    Order Deny,Allow"
echo "    Deny from All"
echo "</Directory>"
echo ""
echo "<Directory /usr/share/roundcubemail/logs>"
echo "    Order Deny,Allow"
echo "    Deny from All"
echo "</Directory>"
echo ""
echo "# Those directories should not be viewed by Web clients."
echo "<Directory /usr/share/roundcubemail/bin/>"
echo "    Order Allow,Deny"
echo "    Deny from all"
echo "</Directory>"
echo "<Directory /usr/share/roundcubemail/plugins/enigma/home/>"
echo "    Order Allow,Deny"
echo "    Deny from all"
echo "</Directory>"
}

create_roundcube_suse_httpd_conf()
{
echo "#"
echo "# Round Cube Webmail is a browser-based multilingual IMAP client"
echo "#"
echo ""
echo "Alias /indimail \"/srv/www/roundcubemail/public_html\""
echo "Alias /installer \"/srv/www/roundcubemail/installer\""
echo ""
echo "# Define who can access the Webmail"
echo "# You can enlarge permissions once configured"
echo ""
echo "<Directory \"/srv/www/roundcubemail/public_html\">"
echo "    <IfModule mod_authz_core.c>"
echo "        # Apache 2.4"
echo "        Options Indexes FollowSymLinks"
echo "        Require ip 127.0.0.1"
echo "        Require all granted"
echo "        Require local"
echo "    </IfModule>"
echo "    <IfModule !mod_authz_core.c>"
echo "        # Apache 2.2"
echo "        Options Indexes FollowSymLinks"
echo "        Order Deny,Allow"
echo "        Deny from all"
echo "        Allow from 127.0.0.1"
echo "        Allow from ::1"
echo "    </IfModule>"
echo "</Directory>"
echo ""
echo "# Define who can access the installer"
echo "# keep this secured once configured"
echo ""
echo "<Directory /srv/www/roundcubemail/installer/>"
echo "    <IfModule mod_authz_core.c>"
echo "        # Apache 2.4"
echo "        Require ip 127.0.0.1"
echo "        Require all granted"
echo "        Require local"
echo "    </IfModule>"
echo "    <IfModule !mod_authz_core.c>"
echo "        # Apache 2.2"
echo "        Order Deny,Allow"
echo "        Deny from all"
echo "        Allow from 127.0.0.1"
echo "        Allow from ::1"
echo "    </IfModule>"
echo "</Directory>"
echo ""
echo "# Those directories should not be viewed by Web clients."
echo "<Directory /srv/www/roundcubemail/bin/>"
echo "    Require all denied"
echo "</Directory>"
echo "<Directory /srv/www/roundcubemail/plugins/enigma/home/>"
echo "    Require all denied"
echo "</Directory>"
}

change_config()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: change_config old_config_file new_config_file" 1>&2
	return 1
fi
conf_file=$1
temp_file=$2
if [ -f $conf_file ] ; then
	if ! $cmp -s $conf_file $temp_file ; then
		echo "saving $temp_file as $conf_file.rpmnew"
		$mv $temp_file "$conf_file".rpmnew
	else
		echo "$conf_file not changed" 1>&2
		$rm -f $temp_file
	fi
else
	$mv $temp_file $conf_file
fi
}

create_mysql_db()
{
if [ -x /usr/sbin/mariadbd ] ; then
	mysqld=/usr/sbin/mariadbd
elif [ -x /usr/libexec/mysqld ] ; then
	mysqld=/usr/libexec/mysqld
elif [ -x /usr/sbin/mysqld ] ; then
	mysqld=/usr/sbin/mysqld
elif [ -x /usr/bin/mysqld ] ; then
	mysqld=/usr/bin/mysqld
else
	echo "mysqld: No such File or directory" 1>&2
	return 1
fi
tmysql_version=`$mysqld --version`
mysql_version=`echo $tmysql_version | awk '{print $3}' 2>&1`
echo $mysql_version | grep MariaDB > /dev/null 2>&1
if [ $? -eq 0 ] ; then
	mysql_version=`echo $mysql_version|cut -d- -f1`
	mariadb=1
	major=$(echo $tmysql_version|awk '{print $3}'|cut -d. -f1)
	minor=$(echo $tmysql_version|awk '{print $3}'|cut -d. -f2)
	if [ $major -ge 11 ] ; then # mariadb ssl fails when using self-signed cert
		mysqld_server_opt="--skip-ssl"
		mysql_client_opt="--skip-ssl-verify-server-cert"
	fi
fi

ps -ef|grep -E "mariadbd|mysqld"|egrep -v "systemctl|grep" > /dev/null 2>&1
if [ $? -ne 0 -o ! -S /var/run/mysqld/mysqld.sock ] ; then
	if [ -x /service/mysql.3306/run ] ; then
		echo "Starting MySQL server"
		/service/mysql.3306/run >/dev/null 2>&1 &
		count=0
		while true
		do
		if [ -f /var/run/mysqld/mysqld.3306.pid ] ; then
				pid=`cat /var/run/mysqld/mysqld.3306.pid`
			elif [ -f /run/mysqld/mysqld.3306.pid ] ; then
				pid=`cat /var/run/mysqld/mysqld.3306.pid`
			else
				pid=""
			fi
			if [ -n "$pid" ] ; then
				echo "Checking MySQLD pid=$pid"
				kill -0 $pid
				if [ $? -eq 0 ] ; then
					echo "$count: found a running MySQL server with pid=$pid" 1>&2
					sleep 2
					break
				else
					echo "$count: Did not find a running MySQL server with pid=$pid" 1>&2
					sleep 5
				fi
			else
				echo "$count: Did not find a running MySQL server" 1>&2
				sleep 5
			fi
			if [ $count -gt 10 ] ; then
				break
			fi
			count=`expr $count + 1`
		done
	fi
fi
if [ -n "$MYSQL_SOCKET" ] ; then
	mysql_sock=$MYSQL_SOCKET
else
	if [ -d /run/mysqld ] ; then
		mysql_sock=/run/mysqld/mysqld.sock
	else
		mysql_sock=/var/run/mysqld/mysqld.sock
	fi
fi
if [ -f /usr/bin/mariadb ] ; then
	mysql=/usr/bin/mariadb
else
	mysql=/usr/bin/mysql
fi
if [ -S $mysqld_sock ] ; then
	echo "adding roundcube user"
	(
		echo "CREATE DATABASE IF NOT EXISTS RoundCube_db;"
		echo "CREATE USER roundcube IDENTIFIED BY 'subscribed';"
		echo "GRANT ALL PRIVILEGES ON RoundCube_db.* TO roundcube;"
		echo "FLUSH PRIVILEGES;"
	) | $mysql -u mysql -p"$PRIV_PASS" $mysql_client_opt mysql
	if [ -f $rcube_base/SQL/mysql.initial.sql ] ; then
		echo "initializing roundcube db"
		$mysql -u roundcube -psubscribed $mysql_client_opt RoundCube_db < $rcube_base/SQL/mysql.initial.sql
	fi
	if [ -f $rcube_base/plugins/sauserprefs/sauserprefs.sql ] ; then
		$mysql -u roundcube -psubscribed $mysql_client_opt RoundCube_db < $rcube_base/plugins/sauserprefs/sauserprefs.sql
	fi
	if [ -x /service/mysql.3306/shutdown ] ; then
		/service/mysql.3306/shutdown
		echo "shutdown MySQL server"
	fi
else
	echo "Couldn't find a running MySQL server: mysqld.sock missing"
fi
}

configure_php_conf()
{
	if [ -f /etc/httpd/conf.d/php.conf ] ; then
		echo "configuring /etc/httpd/conf.d/php.conf"
		if [ ! -f /etc/httpd/conf.d/php.conf.BAK ] ; then
			$mv /etc/httpd/conf.d/php.conf \
				/etc/httpd/conf.d/php.conf.BAK
		fi
		$cp /etc/httpd/conf.d/php.conf.BAK \
			/etc/httpd/conf.d/php.conf
		tmp=$(mktemp -t httpd.tmp.XXXXXXXXXX)
		(
		echo ""
		echo "<Directory /var/www/html>"
		echo "    Options -Indexes +FollowSymLinks +MultiViews"
		echo "    AllowOverride All"
		echo "    Require all granted"
		echo "</Directory>"
		echo ""
		#echo "ProxyPassMatch \"^/(.*\.php(/.*)?)$\" \"unix:$rundir/php-fpm/php-fpm.sock|fcgi://localhost:9000\""
		#echo ""
		echo "<FilesMatch \.php$>"
		echo "    # 2.4.10+ can proxy to unix socket"
		echo "    SetHandler \"proxy:unix:/run/php-fpm/php-fpm.sock|fcgi://localhost:9000\""
		echo "</FilesMatch>"
		) > $tmp
		$sed -i \
			-e "/<\/Files>/ r $tmp" \
			-e "s{^.*SetHandler \"proxy:unix:$rundir/php-fpm/www.sock|fcgi://localhost\"{        SetHandler \"proxy:unix:$rundir/php-fpm/php-fpm.sock|fcgi://localhost:9000\"{g" \
			/etc/httpd/conf.d/php.conf
		/bin/rm -f $tmp
	fi
}

grep openSUSE /etc/os-release > /dev/null 2>&1
if [ $? -eq 0 ] ; then
	is_suse=1
else
	is_suse=0
fi
if [ -d /run ] ; then
	rundir=/run
elif [ -d /var/run ] ; then
	rundir=/var/run
else
	rundir=/run
fi
if [ -n "$MYSQL_SOCKET" ] ; then
	mysql_sock=$MYSQL_SOCKET
else
	mysql_sock=$rundir/mysqld/mysqld.sock
fi
# RoundCube DB setup
if [ $is_suse -eq 1 ] ; then
	rcube_base=/srv/www/roundcubemail
else
	rcube_base=/usr/share/roundcubemail
fi

echo "Creating MySQL DB for roundcube"
if [ ! -d /var/indimail/mysqldb/data/RoundCube_db ] ; then
	create_mysql_db
fi

if [ -f /etc/debian_version ] ; then
	# debian / ubuntu
	httpd_user="www-data"
	httpd_group="www-data"
	php_ini=$(ls /etc/php/*/apache2/php.ini)
elif [ $is_suse -eq 1 ] ; then
	httpd_user="wwwrun"
	httpd_group="www"
	php_ini=$(ls /etc/php*/apache2/php.ini)
else
	# CentOS, Fedora
	httpd_user="apache"
	httpd_group="apache"
	php_ini="/etc/php.ini"
fi

# RoundCube config
if [ $is_suse -eq 1 -a -f /etc/roundcubemail/config.inc.php ] ; then
	if [ ! -f /etc/roundcubemail/config.inc.php.BAK ] ; then
		echo $mv /etc/roundcubemail/config.inc.php /etc/roundcubemail/config.inc.php.BAK
		$mv /etc/roundcubemail/config.inc.php /etc/roundcubemail/config.inc.php.BAK
	fi
fi
# same for all distros
if [ -d /etc/roundcubemail -a ! -f /etc/roundcubemail/config.inc.php ] ; then
	echo "creating /etc/roundcubemail/config.inc.php"
	create_roundcube_php_config > /tmp/config.cnf.$$
	conf_file="/etc/roundcubemail/config.inc.php"
	if [ -f $conf_file ] ; then
		if [ ! -f $conf_file.".BAK" ] ; then
			$mv $conf_file $conf_file".BAK"
		fi
	fi
	change_config $conf_file /tmp/config.cnf.$$
	$chown root:$httpd_group $conf_file
	$chmod 640 $conf_file
	if [ -f /etc/roundcubemail/defaults.inc.php ] ; then
		$chown root:$httpd_group /etc/roundcubemail/defaults.inc.php
		$chmod 640 /etc/roundcubemail/defaults.inc.php
	fi
fi

# same for all distros
# Plugins
fn="/usr/share/roundcubemail/plugins/iwebadmin/config.inc.php"
if [ -f $fn ] ; then
	echo "configuring $fn"
	if [ ! -f "$fn".BAK ] ; then
		$mv $fn "$fn.".BAK
	fi
	$cp "$fn.".BAK $fn
	$sed -i \
		-e "s}$rcmail_config\['iwebadmin_path'\].*}$rcmail_config\['iwebadmin_path'\] = 'https://localhost/cgi-bin/iwebadmin/';}g" \
	$fn
fi
		
fn="/usr/share/roundcubemail/plugins/sauserprefs/config.inc.php"
if [ -f $fn ] ; then
	echo "configuring $fn"
	if [ ! -f "$fn".BAK ] ; then
		$mv $fn "$fn.".BAK
	fi
	$cp "$fn.".BAK $fn
	$sed -i \
		-e "s}$rcmail_config\['sauserprefs_db_dsnw'\].*}$rcmail_config\['sauserprefs_db_dsnw'\] = 'mysql://roundcube:subscribed@localhost/RoundCube_db';}g" \
	$fn
fi

if [ -n "$php" -a -n "$php_ini" -a -f $php_ini ] ; then
	echo "configuring $php_ini"
	if [ ! -f "$php_ini".BAK ] ; then
		$mv $php_ini "$php_ini".BAK
	fi
	$cp "$php_ini".BAK $php_ini
	$sed -i \
		-e "s}upload_max_filesize.*}upload_max_filesize = 5M}g" \
		-e "s}session.auto_start.*}session.auto_start = Off}g" \
		-e "s}^session.gc_maxlifetime.*}session.gc_maxlifetime = 21600}g" \
		-e "s};.*session.gc_divisor.*}session.gc_divisor = 500}g" \
		-e "s}session.gc_probability.*}session.gc_probability = 1}g" \
		-e "s};.*short_open_tag}short_open_tag = On}g" \
		-e "s}max_execution_time.*}max_execution_time = 60}g" \
		-e "s}pdo_mysql.default_socket=.*}pdo_mysql.default_socket=$mysql_sock}g" \
		-e "s};sendmail_path.*=.*}sendmail_path=/usr/sbin/sendmail -t -i}g" \
		-e "s};openssl.cafile=.*}openssl.cafile=/etc/indimail/certs/servercert.pem}g" \
      	-e "s};openssl.capath=.*}openssl.capath=/etc/indimail/certs}g" \
	$php_ini
	$php -r "print_r(openssl_get_cert_locations());"
else
	echo "$php_ini not found"
fi

if [ -f /etc/httpd/conf.d/roundcubemail.conf ] ; then
	rcube_httpd_conf=/etc/httpd/conf.d/roundcubemail.conf
elif [ -f /etc/apache2/conf.d/roundcubemail.conf ] ; then
	rcube_httpd_conf=/etc/apache2/conf.d/roundcubemail.conf
else
	rcube_httpd_conf=""
fi
if [ -n "$rcube_httpd_conf" -a $is_suse -eq 1 ] ; then
	if [ -f $rcube_httpd_conf -a ! -f "$rcube_httpd_conf".BAK ] ; then
		$mv $rcube_httpd_conf "$rcube_httpd_conf".BAK
	fi
	echo "Creating $rcube_httpd_conf for openSUSE"
	create_roundcube_suse_httpd_conf > $rcube_httpd_conf
elif [ -n "$rcube_httpd_conf" -a -f "$rcube_httpd_conf" ] ; then
	echo "configuring $rcube_httpd_conf"
	if [ ! -f "$rcube_httpd_conf".BAK ] ; then
		$mv $rcube_httpd_conf "$rcube_httpd_conf".BAK
	fi
	$cp "$rcube_httpd_conf".BAK $rcube_httpd_conf
	$sed -i \
		-e "s}Alias /roundcubemail }Alias /indimail }g" \
		-e "/Require local/ i \        Require ip 127.0.0.1" \
		-e "/Require local/ i \        Require all granted" \
		$rcube_httpd_conf
	$chown root:root $rcube_httpd_conf
	$chmod 644 $rcube_httpd_conf
fi

if [ -f /etc/httpd/conf.d/ssl.conf ] ; then
	ssl_cnf=/etc/httpd/conf.d/ssl.conf
elif [ -f /etc/apache2/ssl-global.conf ] ; then
	ssl_cnf=/etc/apache2/ssl-global.conf
else
	ssl_cnf=""
fi

if [ -n "$ssl_cnf" -a -f $ssl_cnf ] ; then
	echo "configuring $ssl_cnf"
	if [ ! -f "$ssl_cnf".BAK ] ; then
		$mv $ssl_cnf "$ssl_cnf".BAK
	fi
	$cp "$ssl_cnf".BAK $ssl_cnf
	if [ $is_suse -eq 1 ] ; then
		$sed -i \
			-e "s{.*#SSLCertificateFile /etc/apache2/ssl.crt/server.crt{SSLCertificateFile /etc/indimail/certs/servercert.pem{g" \
		$ssl_cnf
	else
		$sed -i \
			-e "s}^#ServerName www.example.com:443}ServerName indimail.org:443}g" \
			-e "s}^SSLCertificateFile.*}SSLCertificateFile /etc/indimail/certs/servercert.pem}g" \
			-e 's/^SSLCertificateKeyFile./#&/' \
		$ssl_cnf
	fi
fi
if [ -f /etc/centos-release -o -f /etc/almalinux-release -o -f /etc/rockylinux-release -o -f /etc/rocky-release -o -f /etc/fedora-release -o -f /etc/oracle-release ] ; then
	if [ -f /etc/oracle-release ] ; then
		t=$(cat /etc/oracle-release|awk '{print $1}')
	elif [ -f /etc/redhat-release ] ; then
		t=$(cat /etc/redhat-release|awk '{print $1}')
	else
		if [ -f /etc/centos-release ] ; then
			t="CentOS"
		elif [ -f /etc/almalinux-release ] ; then
			t="AlmaLinux"
		elif [ -f /etc/rockylinux-release ] ; then
			t="RockyLinux"
		elif [ -f /etc/rocky-release ] ; then
			t="Rocky"
		elif [ -f /etc/fedora-release ] ; then
			t="Fedora"
		else
			t="Unknown"
		fi
	fi
	if [ "$t" = "CentOS" ] ; then
		os_release=$(cat /etc/centos-release|awk '{print $4}'|cut -d.  -f1)
	elif [ "$t" = "AlmaLinux" ] ; then
		os_release=$(cat /etc/almalinux-release|awk '{print $3}'|cut -d.  -f1)
	elif [ "$t" = "RockyLinux" ] ; then
		os_release=$(cat /etc/rockylinux-release|awk '{print $3}'|cut -d.  -f1)
	elif [ "$t" = "Rocky" ] ; then
		os_release=$(cat /etc/rocky-release|awk '{print $4}'|cut -d.  -f1)
	elif [ "$t" = "Fedora" ] ; then
		os_release=$(cat /etc/fedora-release|awk '{print $3}'|cut -d.  -f1)
	elif [ "$t" = "Oracle" ] ; then
		os_release=$(cat /etc/oracle-release |awk '{print $5}'|cut -d. -f1)
	elif [ "$t" = "Red" ] ; then
		os_release=$(cat /etc/redhat-release |sed -e 's{.*release{{' -e 's{.*Release{{'|awk '{print $1}')
	else
		echo "Unknown Redhat OS release" 1>&2
		exit 1
	fi
	configure_php_conf

	case "$os_release" in
		7|8|9)
		echo "configuring /etc/httpd/conf.d/roundcubemail.conf for $t $os_release"
		fn="/etc/httpd/conf.d/roundcubemail.conf"
		if [ -f $fn -a ! -f "$fn".BAK ] ; then
			$mv $fn "$fn".BAK
		fi
		create_roundcube_centos_httpd_conf > $fn
		fn="/etc/httpd/conf.modules.d/00-mpm.conf"
		if [ -f $fn ] ; then
			echo "configuring $fn"
			if [ ! -f "$fn".BAK ] ; then
				$mv $fn "$fn".BAK
			fi
			$cp "$fn".BAK $fn
			sed -i \
				-e 's{LoadModule mpm_prefork_module.*{#&{g' \
				-e 's{#LoadModule mpm_event_module{LoadModule mpm_event_module{g' \
					$fn
		fi
		;;
		*)
		;;
	esac
elif [ -f /etc/debian_version ] ; then
	if [ ! -f /etc/apache2/sites-available/roundcubemail.conf ] ; then
		echo "configuring /etc/apache2/sites-available/roundcubemail.conf"
		create_roundcube_httpd_conf > /etc/apache2/sites-available/roundcubemail.conf
		a2ensite roundcubemail.conf
	fi
	fn="/etc/apache2/sites-available/000-default.conf"
	if [ -f $fn ] ; then
		if [ ! -f "$fn".BAK ] ; then
			$mv $fn "$fn".BAK
		fi
		$cp "$fn".BAK $fn
		echo "configuring $fn"
		# apache2 on debian by default uses mod_php. You have to do this
		# in order for apache2 to use php-fpm
		tmp=$(mktemp -t apache2.tmp.XXXXXXXXXX)
		(
		echo "	ScriptAlias /cgi-bin/ /var/www/cgi-bin/"
		echo ""
		echo "	<Directory /var/www/html>"
		echo "		Options -Indexes +FollowSymLinks +MultiViews"
		echo "		AllowOverride All"
		echo "		Require all granted"
		echo "	</Directory>"
		echo ""
		echo "	<Directory /var/www/cgi-bin>"
		echo "		Require all granted"
		echo "		AllowOverride None"
		echo "		Options ExecCGI"
		echo "	</Directory>"
		echo ""
		echo "	<FilesMatch \.php$>"
		echo "		# 2.4.10+ can proxy to unix socket"
		echo "		SetHandler \"proxy:unix:/run/php-fpm/php-fpm.sock|fcgi://localhost/\""
		echo "		# Else we can just use a tcp socket:"
		echo "		#SetHandler \"proxy:fcgi://127.0.0.1:9000\""
		echo "	</FilesMatch>"
		) > $tmp
		$sed -i \
			-e "/DocumentRoot/ r $tmp" \
			-e "s}#ServerName www.example.com}ServerName mail.indimail.org}g" \
			-e "s}ServerAdmin webmaster@localhost}ServerAdmin root@localhost}g" \
		$fn
		$rm -f $tmp
		unset tmp
		a2enmod cgid
	fi
	fn="/etc/apache2/sites-available/default-ssl.conf"
	if [ -f $fn ] ; then
		if [ ! -f "$fn".BAK ] ; then
			$mv $fn "$fn".BAK
		fi
		$cp "$fn".BAK $fn
		echo "configuring /etc/apache2/sites-available/default-ssl.conf"
		$sed -i \
			-e "s}ServerAdmin.*@.*}ServerAdmin root@localhost}g" \
			-e "s}SSLCertificateFile.*/etc.*}SSLCertificateFile	/etc/indimail/certs/servercert.pem}g" \
			-e 's/SSLCertificateKeyFile./#&/' \
		$fn
		a2ensite default-ssl.conf
	fi
fi

echo "Adding qcerts as supplementary group to $httpd_group"
/usr/bin/getent passwd $httpd_user >/dev/null && /usr/sbin/usermod -aG qcerts $httpd_user

# setting up php-fpm on openSUSE distributions is crazy
# the standard directories are too different. /srv/www instead
# of /var/www. I find I have wasted too much time to make things
# work. So I'm giving up on suse distributions. If anyone of you
# reads this and can fix things, I owe you beer.

#if [ $is_suse -eq 1 ] ; then
#	echo I give up
#	exit 0
#fi

# if you want to grow old fast, deal with way things
# are configured when using php
# today there is php8, tomorrow it will be php9, php10, ...
# why can't there be a proper standard in the www world.
if [ -f /etc/php-fpm.d/www.conf ] ; then
	php_fpm_www_conf=/etc/php-fpm.d/www.conf
elif [ -f /etc/php9/fpm/php-fpm.d/www.conf.default ] ; then
	php_fpm_www_conf=/etc/php9/fpm/php-fpm.d/www.conf
elif [ -f /etc/php8/fpm/php-fpm.d/www.conf.default ] ; then
	php_fpm_www_conf=/etc/php8/fpm/php-fpm.d/www.conf
elif [ -f /etc/php7/fpm/php-fpm.d/www.conf.default ] ; then
	php_fpm_www_conf=/etc/php7/fpm/php-fpm.d/www.conf
elif [ -f /etc/php9/fpm/php-fpm.d/www.conf ] ; then
	php_fpm_www_conf=/etc/php9/fpm/php-fpm.d/www.conf
elif [ -f /etc/php8/fpm/php-fpm.d/www.conf ] ; then
	php_fpm_www_conf=/etc/php8/fpm/php-fpm.d/www.conf
elif [ -f /etc/php7/fpm/php-fpm.d/www.conf ] ; then
	php_fpm_www_conf=/etc/php7/fpm/php-fpm.d/www.conf
else #debian /etc/php/7.3/fpm/pool.d/www.conf
	php_fpm_www_conf=`ls /etc/php/*/fpm/pool.d/www.conf 2>/dev/null`
	php_fpm_conf=$(ls /etc/php/*/fpm/php-fpm.conf 2>/dev/null)
fi
if [ -z "$php_fpm_conf" -a -f /etc/php-fpm.conf ] ; then
	php_fpm_conf=/etc/php-fpm.conf
	echo "fixing pid in $php_fpm_conf"
	$sed -i \
		-e "s{^;pid =.*{pid = $rundir/php-fpm/php-fpm.pid{g" \
		-e "s{^pid =.*{pid = $rundir/php-fpm/php-fpm.pid{g" \
		$php_fpm_conf
fi
if [ $is_suse -eq 1 ] ; then
	if [ -d /etc/php10 ] ; then #hopefully when suse comes with php10, php9, this script will still work
		php_ver=php10
	elif [ -d /etc/php9 ] ; then
		php_ver=php9
	elif [ -d /etc/php8 ] ; then
		php_ver=php8
	else
		php_ver=php7
	fi
	if [ -f /etc/$php_ver/fpm/php-fpm.conf.default ] ; then
		$cp /etc/$php_ver/fpm/php-fpm.conf.default /etc/$php_ver/fpm/php-fpm.conf
	fi
	if [ -f /etc/$php_ver/fpm/php-fpm.conf ] ; then
		echo "fixing pid in /etc/$php_ver/fpm/php-fpm.conf"
		$sed -i -e "s{^;pid =.*{pid = $rundir/php-fpm/php-fpm.pid{g" \
			/etc/$php_ver/fpm/php-fpm.conf
	fi
	if [ -f "$php_fpm_www_conf".default ] ; then
		echo "Copying $php_fpm_www_conf.default to $php_fpm_www_conf"
		$cp "$php_fpm_www_conf".default $php_fpm_www_conf
	fi

	if [ -f /etc/apache2/loadmodule.conf ] ; then
		echo "Configuring /etc/apache2/loadmodule.conf"
		grep "php.*"_module /etc/apache2/loadmodule.conf > /dev/null
		if [ $? -ne 0 ] ; then
			echo "fixing /etc/apache2/loadmodule.conf"
			if [ "$php_ver" = "php7" ] ; then
				echo "LoadModule php7_module /usr/lib64/apache2/mod_php7.so" \
					>> /etc/apache2/loadmodule.conf
			else
				echo "LoadModule php_module /usr/lib64/apache2/mod_"$php_ver".so" \
					>> /etc/apache2/loadmodule.conf
			fi
		fi
	fi
	if [ -f /etc/apache2/default-server.conf ] ; then
		echo "fixing DocumentRoot in /etc/apache2/default-server.conf"
		if [ ! -f /etc/apache2/default-server.conf.BAK ] ; then
			mv /etc/apache2/default-server.conf /etc/apache2/default-server.conf.BAK
			cp /etc/apache2/default-server.conf.BAK /etc/apache2/default-server.conf
		fi
		sed -i -e "s}/srv/www}/var/www}g" -e "s}htdocs}html}g" \
			/etc/apache2/default-server.conf
	fi
fi

if [ -n "$php_fpm_www_conf" -a -f "$php_fpm_www_conf" ] ; then
	echo "fixing $php_fpm_www_conf"
	$sed -i \
		-e "s}^user = nobody}user = $httpd_user}" \
		-e "s}^group = nobody}group = $httpd_group}" \
		-e 's}listen = .*}listen = /run/php-fpm/php-fpm.sock}' \
		-e "s};listen.owner = nobody}listen.owner = $httpd_user}g" \
		-e "s};listen.group = nobody}listen.group = $httpd_group}g" \
		-e 's};listen.mode = 0660}listen.mode = 0660}g' \
	$php_fpm_www_conf
fi
if [ -n "$php_fpm_conf" -a -f "$php_fpm_conf" ] ; then
	echo "fixing $php_fpm_conf"
	$sed -i -e "s{^pid =.*{pid = $rundir/php-fpm/php-fpm.pid{g" \
		$php_fpm_conf
fi
#
# create supervised services for apache2 and php-fpm under /service
# have them in down state so that they don't get started when
# invoked as indimail/indimail-mta containers
#
php_fpm=$(ls /usr/sbin/php-fpm* 2>/dev/null)
if [ -n "$php_fpm" -a ! -d /service/php-fpm ] ; then
	if [ -n "$php_fpm_www_conf" -a -f "$php_fpm_www_conf" ] ; then
		sockname=$(grep "^listen =" $php_fpm_www_conf |cut -d= -f2)
		sockdir=$(dirname $sockname)
		echo "Creating supervised service for php-fpm using socket dir [$sockdir]"
		mkdir -p /service/php-fpm/log
		touch /service/php-fpm/down
		(
		echo "#!/bin/sh"
		echo "# created by roundcube_config for indimail+roundcube docker container"
		echo "# service started by docker-entrypoint"
		echo "#"
		echo "exec 2>&1"
		echo "mkdir -p $sockdir"
		echo "exec $php_fpm -O -F"
		) > /service/php-fpm/run
		chmod +x /service/php-fpm/run
		(
		echo "#!/bin/sh"
		echo "exec /usr/bin/setuidgid qmaill \\"
		echo "  /usr/sbin/multilog t /var/log/svc/php-fpm"
		) > /service/php-fpm/log/run
		chmod +x /service/php-fpm/log/run
	else
		echo "couldn't find php-fpm config"
	fi
else
	echo "couldn't find php-fpm"
fi

if [ ! -d /service/httpd ] ; then
	if [ -x /usr/sbin/httpd ] ; then
		echo "Creating supervised service for apache2"
		mkdir -p /service/httpd/log
		touch /service/httpd/down
		(
		echo "#!/bin/sh"
		echo "# created by roundcube_config for indimail+roundcube docker container"
		echo "# service started by docker-entrypoint"
		echo "#"
		echo "if [ ! -d /usr/share/roundcubemail/config -a ! -L /usr/share/roundcubemail/config ] ; then"
		echo "  echo \"ln -s /etc/roundcubemail /usr/share/roundcubemail/config\""
		echo "  ln -s /etc/roundcubemail /usr/share/roundcubemail/config"
		echo "fi"
		echo ""
		echo "if [ ! -d $rundir/lock ] ; then"
		echo "  mkdir -p $rundir/lock"
		echo "fi"
		echo "if [ ! -d $rundir/httpd ] ; then"
		echo "  mkdir -p $rundir/httpd"
		echo "fi"
		echo ""
		echo "exec /usr/sbin/httpd -DFOREGROUND"
		) > /service/httpd/run
		chmod +x /service/httpd/run
		(
		echo "#!/bin/sh"
		echo "exec /usr/bin/setuidgid qmaill \\"
		echo "  /usr/sbin/multilog t /var/log/svc/httpd"
		) > /service/httpd/log/run
		chmod +x /service/httpd/log/run
	elif [ -x /usr/sbin/apache2 ] ; then
		echo "Creating supervised service for apache2"
		mkdir -p /service/httpd/log
		touch /service/httpd/down
		(
		echo "#!/bin/sh"
		echo "# created by roundcube_config for indimail+roundcube docker container"
		echo "# service started by docker-entrypoint"
		echo "#"
		echo "if [ ! -d /usr/share/roundcubemail/config -a ! -L /usr/share/roundcubemail/config ] ; then"
		echo "  echo \"ln -s /etc/roundcubemail /usr/share/roundcubemail/config\""
		echo "  ln -s /etc/roundcubemail /usr/share/roundcubemail/config"
		echo "fi"
		echo ""
		echo "if [ ! -d $rundir/lock ] ; then"
		echo "  mkdir -p $rundir/lock"
		echo "fi"
		echo ""
		echo "exec fghack /usr/sbin/apachectl -DFOREGROUND"
		) > /service/httpd/run
		chmod +x /service/httpd/run
		(
		echo "#!/bin/sh"
		echo "exec /usr/bin/setuidgid qmaill \\"
		echo "  /usr/sbin/multilog t /var/log/svc/httpd"
		) > /service/httpd/log/run
		chmod +x /service/httpd/log/run
		(
		echo "#!/bin/sh"
		echo "# created by roundcube_config for indimail+roundcube docker container"
		echo "# service started by docker-entrypoint"
		echo "#"
		echo "exec /usr/sbin/apachectl stop"
		) > /service/httpd/shutdown
		chmod +x /service/httpd/shutdown
	else
		echo "Couldn't find httpd/apache2" 1>&2
	fi
fi

if [ -d /var/www/html ] ; then
	echo "<?php phpinfo(); ?>" > /var/www/html/info.php
elif [ -d /srv/www/htdocs ] ; then
	echo "<?php phpinfo(); ?>" > /srv/www/htdocs/info.php
fi

if [ -x /usr/bin/crontab ] ; then
	tmp=$(mktemp -t crontab.tmp.XXXXXXXXXX)
	echo "Getting existing crontab entry for root"
	crontab -u root -l 2>/dev/null | \
		$sed "/$(echo $rcube_base| $sed -e 's/\//\\\//g')\/bin\/cleandb\.sh/d" > "${tmp}"
	echo "18 11 * * * $rcube_base/bin/cleandb.sh > /dev/null" >> "${tmp}"
	echo "Adding crontab entry for root"
	crontab -u root "${tmp}"
	$rm -f "${tmp}"
	unset tmp
	$chmod +x $rcube_base/bin/cleandb.sh
fi
echo "added selinux module for roundcubemail"
/usr/sbin/svctool --config=selinux --module=roundcubemail
exit 0
