#!/bin/sh -e
# vim:syntax=sh

usage()
{
	echo "`basename $0` <new email>"
	echo "Change admin passsowrd for Plesk apache config"
	exit 1
}

die()
{
	echo ERROR: $*
	exit 1
}

conf_getvar()
{
    cat $1 | perl -n -e '$p="'$2'"; print $1 if m/^$p\s+(.*)/'
}

cnf="/etc/httpd/conf.d/zz010_psa_httpd.conf"

# config not found check for psa.conf
if [ ! -f "$cnf" ]; then
	[ -s "/etc/psa/psa.conf" ] || die "apache config and /etc/psa/psa.conf are not exists "
	HTTPD_INCLUDE_D=`conf_getvar "/etc/psa/psa.conf" "HTTPD_INCLUDE_D"`
	cnf="$HTTPD_INCLUDE_D/zz010_psa_httpd.conf"
fi

email="$1"

# Sanity checks
[ -n "$1" ] || usage
[ -f "$cnf" ] || die "config file '$cnf' not found"
grep -q "^ServerAdmin[[:space:]]" $cnf || die "cannot find the ServerAdmin directive in '$cnf'"

tempfile=`mktemp /tmp/httpdXXXXXX`
sed -e 's/^ServerAdmin[ \t].*$/ServerAdmin '$email'/g' $cnf > $tempfile && \
mv $tempfile $cnf
# Fix perms and context
chown 0:0 $cnf
chmod 0644 $cnf
restorecon $cnf >/dev/null 2>&1  || :
# Now stop/start for avoid race
/usr/local/psa/admin/sbin/websrvmng --stop || :
sleep 2
/usr/local/psa/admin/sbin/websrvmng --start
