#!/bin/bash

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# extract value of a MySQL option from config files
# Usage: get_mysql_option SECTION VARNAME DEFAULT
# result is returned in $result
# We use my_print_defaults which prints all options from multiple files,
# with the more specific ones later; hence take the last match.
get_mysql_option(){
	result=`/usr/bin/my_print_defaults "$1" | sed -n "s/^--$2=//p" | tail -n 1`
	if [ -z "$result" ]; then
	    # not found, use default
	    result="$3"
	fi
}

# Se intenta prender mysql en caso de que esté apagado
/sbin/service mysqld status > /dev/null 2>&1
if [ ! "$?" == "0" ] ; then
    /sbin/service mysqld start > /dev/null 2>&1
fi

get_mysql_option mysqld datadir "/var/lib/mysql"
datadir="$result"
get_mysql_option mysqld socket "$datadir/mysql.sock"
socketfile="$result"
get_mysql_option mysqld_safe log-error "/var/log/mysqld.log"
errlogfile="$result"
get_mysql_option mysqld_safe pid-file "/var/run/mysqld/mysqld.pid"
mypidfile="$result"

BACKTITLE="Elastix password configuration"
PASSWD_PATH="/etc/elastix.conf"
OPTFILE="/tmp/option.$$"

elastix_mysql_init(){
	
	if [ -e $PASSWD_PATH ] ; then
	    if [ -e "/etc/amportal.conf" ] ; then
    	    	# Prompt for the MySQL password for this system
            	elastix_prompt_mysql_passwd
            	ret=$?
            	if [ $ret -ne 0 ] ; then
            		return $ret
            	fi
	    else
		echo "Configuration file /etc/amportal.conf not present"
		return 1
	    fi
	else
	    echo "Password configuration /etc/elastix.conf not present."
	    return 1
	fi

	# Prompt for web passwords on first boot
	elastix_prompt_web_passwd
	ret=$?

	return $ret
}

elastix_prompt_mysql_passwd(){
	DIALOG_PURPOSE="The Elastix system uses the open-source database engine MySQL for storage \
of important telephony information. In order to protect your data, a master password must \
be set up for the database.\n\n\
This screen will now ask for a password for the 'root' account of MySQL.\n\n"
	# Read and set new MySQL root password
	while [ "$MYSQL_PASSWD1" == "" ] ; do
	    MYSQL_PASSWD1=""
	    MYSQL_PASSWD2=""
	    while [ "$MYSQL_PASSWD1" == "" ] ; do
	        dialog --output-fd 3 --backtitle "$BACKTITLE (Screen 1 of 6)" --insecure --passwordbox "$DIALOG_PURPOSE Please enter your new MySQL root password:" 16 70 3>$OPTFILE
		if [ $? -ne 0 ] ; then
		    exit 0
		fi
	        MYSQL_PASSWD1=`cat $OPTFILE`
	        if [ "$MYSQL_PASSWD1" == "" ] ; then
	            dialog --backtitle "$BACKTITLE" --msgbox "MySQL root password must be nonempty." 7 40
		else
			if cat $OPTFILE | perl -ne 'exit(1) if /^([a-zA-Z0-9 .&-@=_!<>]+)$/; exit(0);' ; then
				dialog --backtitle "$BACKTITLE" --msgbox "Admin password may only contain alphanumeric characters, spaces, or the following: .&-@=_!<>]." 7 40
				MYSQL_PASSWD1=""
			fi
	        fi
	    done
	    while [ "$MYSQL_PASSWD2" == "" ] ; do
	        dialog --output-fd 3 --backtitle "$BACKTITLE (Screen 2 of 6)" --insecure --passwordbox "Please (re)confirm your new MySQL root password:" 10 70 3>$OPTFILE
	        if [ $? -ne 0 ] ; then
		   exit 0
		fi	
		MYSQL_PASSWD2=`cat $OPTFILE`
	    done
	    if [ "$MYSQL_PASSWD1" != "$MYSQL_PASSWD2" ] ; then
	        dialog --backtitle "$BACKTITLE" --msgbox "Password and confirmation do not match!" 7 40
	        MYSQL_PASSWD1=""
	        MYSQL_PASSWD2=""
	    fi
	done
	
	while [ "$MYSQL_OLDPASSWD" == "" ] ; do
             dialog --output-fd 3 --backtitle "$BACKTITLE (Screen 3 of 6)" --insecure --passwordbox "Please enter the old MySQL root password:" 10 70 3>$OPTFILE
	     if [ $? -ne 0 ] ; then
                 exit 0
             fi
             MYSQL_OLDPASSWD=`cat $OPTFILE`
             if [ "$MYSQL_OLDPASSWD" == "" ] ; then
                 dialog --backtitle "$BACKTITLE" --msgbox "MySQL root password must be nonempty." 7 40
             else
                 if cat $OPTFILE | perl -ne 'exit(1) if /^([a-zA-Z0-9 .&-@=_!<>]+)$/; exit(0);' ; then
                       dialog --backtitle "$BACKTITLE" --msgbox "Admin password may only contain alphanumeric characters, spaces, or the following: .&-@=_!<>]." 7 40
                        MYSQL_OLDPASSWD=""
                 fi
             fi
        done

	rm -f $OPTFILE	
	if ! /usr/bin/mysqladmin -u root "-p$MYSQL_OLDPASSWD" password "$MYSQL_PASSWD1" ; then
	    echo "Unable to change root password for MySQL - wrong password!"
	    return 1
	fi
	
	echo "UPDATE mysql.user SET Password=PASSWORD('$MYSQL_PASSWD1') WHERE User='root';" | mysql -u root "-p$MYSQL_PASSWD1"
	ret=$?
	if [ $? -ne 0 ]; then
	    echo "Unable to set root password (2) for MySQL - password already set or server not running!"
	    return 1
	fi
	echo "FLUSH PRIVILEGES;" | mysql -u root "-p$MYSQL_PASSWD1"
	
	cat $PASSWD_PATH | sed "s/mysqlrootpwd=$MYSQL_OLDPASSWD/mysqlrootpwd=$MYSQL_PASSWD1/" > /tmp/elastix.conf.tmp
        mv /tmp/elastix.conf.tmp /etc/elastix.conf
	# ****Add the user cyrus with the command saslpasswd2 ***************
	echo "$MYSQL_PASSWD1" | /usr/sbin/saslpasswd2 -c cyrus -u example.com
	ret=$?
	if [ $? -ne 0 ]; then
		echo "Unable to set cyrus password for cyrus admin!"
	    return 1
	fi

	# Cambiar permisos del archivo /etc/sasldb2 a 644 
	chmod 644 /etc/sasldb2
	cat $PASSWD_PATH | sed "s/cyrususerpwd=$MYSQL_OLDPASSWD/cyrususerpwd=$MYSQL_PASSWD1/" > /tmp/elastix.conf.tmp
        mv /tmp/elastix.conf.tmp /etc/elastix.conf
	# *******************************************************************
	
	chmod 600 $PASSWD_PATH
	chown asterisk.asterisk $PASSWD_PATH
	echo "The password for mysql and cyrus admin were successfully changed!"
	sleep 3
}

elastix_prompt_web_passwd() {
	DIALOG_PURPOSE="Several Elastix components have administrative interfaces that can be used \
through the Web. A web login password must be set for these components in order to prevent \
unauthorized access to these administration interfaces.\n\n\
This screen will now ask for a password for user 'admin' that will be used for: Elastix Web Login, FreePBX, VTiger, A2Billing and FOP.\n\n"
	
	MYSQL_PASSWD1=`grep mysqlrootpwd= /etc/elastix.conf | sed 's/^mysqlrootpwd=//'`
        FREEPBX_OLDPASSWD1=`grep '^AMPDBPASS=' /etc/amportal.conf | sed 's/^AMPDBPASS=//'`
        FOP_OLDPASSWD=`grep '^FOPPASSWORD=' /etc/amportal.conf | sed 's/^FOPPASSWORD=//'`
	ARI_OLDPASSWD=`grep '^ARI_ADMIN_PASSWORD=' /etc/amportal.conf | sed 's/^ARI_ADMIN_PASSWORD=//'`
	OLDDBPASS=`grep '^dbpass = ' /etc/asterisk/res_mysql.conf | sed 's/^dbpass = //'`
        OLDCBMYSQL=`grep '^password=' /etc/asterisk/cbmysql.conf | sed 's/^password=//'`
	OLDCDRMYSQL=`grep '^password = ' /etc/asterisk/cdr_mysql.conf | sed 's/^password = //'`
	OLDAMIPWD=`grep '^amiadminpwd=' /etc/elastix.conf | sed 's/^amiadminpwd=//'`
	AMIPASS="yes"
	if [ "$OLDAMIPWD" == "" ] ; then
        	OLDAMIPWD="elastix456"
		AMIPASS="no"
	fi

	# Read and set new FreePBX admin password. This procedure works with FreePBX 2.7.0
	# This password will also be used for Elastix login, VTiger and A2Billing
	while [ "$FREEPBX_PASSWD1" == "" ] ; do
	    FREEPBX_PASSWD1=""
	    FREEPBX_PASSWD2=""
	    while [ "$FREEPBX_PASSWD1" == "" ] ; do
	        dialog --output-fd 3 --backtitle "$BACKTITLE (Screen 4 of 6)" --insecure --passwordbox "$DIALOG_PURPOSE Please enter your new password for freePBX 'admin':" 16 70 3>$OPTFILE
		if [ $? -ne 0 ] ; then
                   exit 0
                fi
	        FREEPBX_PASSWD1=`cat $OPTFILE`
	        if [ "$FREEPBX_PASSWD1" == "" ] ; then
	            dialog --backtitle "$BACKTITLE" --msgbox "Admin password must be nonempty." 7 40
		else 
			if cat $OPTFILE | perl -ne 'exit(1) if /^([a-zA-Z0-9 .&-@=_!<>]+)$/; exit(0);' ; then
				dialog --backtitle "$BACKTITLE" --msgbox "Admin password may only contain alphanumeric characters, spaces, or the following: .&-@=_!<>]." 7 40
				FREEPBX_PASSWD1=""
			fi
	        fi
	    done
	    while [ "$FREEPBX_PASSWD2" == "" ] ; do
	        dialog --output-fd 3 --backtitle "$BACKTITLE (Screen 5 of 6)" --insecure --passwordbox "Please (re)confirm your new password for freePBX 'admin':" 10 70 3>$OPTFILE
		if [ $? -ne 0 ] ; then
                   exit 0
                fi
	        FREEPBX_PASSWD2=`cat $OPTFILE`
	    done
	    if [ "$FREEPBX_PASSWD1" != "$FREEPBX_PASSWD2" ] ; then
	        dialog --backtitle "$BACKTITLE" --msgbox "Password and confirmation do not match!" 7 40
	        FREEPBX_PASSWD1=""
	        FREEPBX_PASSWD2=""
	    fi
	done

	while [ "$FREEPBX_OLDPASSWD2" == "" ] ; do
            dialog --output-fd 3 --backtitle "$BACKTITLE (Screen 6 of 6)" --insecure --passwordbox "Please enter the old password for freePBX 'admin':" 10 70 3>$OPTFILE
            if [ $? -ne 0 ] ; then
                exit 0
            fi
	    FREEPBX_OLDPASSWD2=`cat $OPTFILE`
            if [ "$FREEPBX_OLDPASSWD2" == "" ] ; then
                dialog --backtitle "$BACKTITLE" --msgbox "Admin password must be nonempty." 7 40
            else
                if cat $OPTFILE | perl -ne 'exit(1) if /^([a-zA-Z0-9 .&-@=_!<>]+)$/; exit(0);' ; then
                     dialog --backtitle "$BACKTITLE" --msgbox "Admin password may only contain alphanumeric characters, spaces, or the following: .&-@=_!<>]." 7 40
                     FREEPBX_OLDPASSWD2=""
                fi
            fi
        done
	
	rm -f $OPTFILE
	
	if [ ! "$FREEPBX_OLDPASSWD1" == "$FREEPBX_OLDPASSWD2" ] ; then
		echo "Wrong admin password!"
		return 1
	fi

	echo "UPDATE asterisk.ampusers SET password_sha1=sha1('$FREEPBX_PASSWD1') WHERE username = 'admin';" | mysql -u root "-p$MYSQL_PASSWD1"
	ret=$?
	if [ $? -ne 0 ]; then
	    echo "Unable to set admin password for FreePBX !"
	    return 1
	fi
	
	# Use the same password for freePBX login and for updating /etc/amportal.conf
	echo "GRANT USAGE ON *.* TO 'asteriskuser'@'localhost' IDENTIFIED BY '$FREEPBX_PASSWD1'" | mysql -u root "-p$MYSQL_PASSWD1"
	ret=$?
	if [ $? -ne 0 ]; then
	    echo "Unable to set database password for FreePBX !"
	    return 1
	fi
	FREEPBX_PASSWD_ESC=`echo $FREEPBX_PASSWD1 | sed "s/&/\\\\\\&/g"`
	cat /etc/amportal.conf | sed "s/AMPDBPASS=$FREEPBX_OLDPASSWD1/AMPDBPASS=$FREEPBX_PASSWD_ESC/" > /tmp/amportal.conf.tmp
	mv /tmp/amportal.conf.tmp /etc/amportal.conf
	cat /etc/amportal.conf | sed "s/AMPMGRPASS=$OLDAMIPWD/AMPMGRPASS=$FREEPBX_PASSWD_ESC/" > /tmp/amportal.conf.tmp
        mv /tmp/amportal.conf.tmp /etc/amportal.conf
	cat /etc/amportal.conf | sed "s/FOPPASSWORD=$FOP_OLDPASSWD/FOPPASSWORD=$FREEPBX_PASSWD_ESC/" > /tmp/amportal.conf.tmp
	mv /tmp/amportal.conf.tmp /etc/amportal.conf
	cat /etc/amportal.conf | sed "s/ARI_ADMIN_PASSWORD=$ARI_OLDPASSWD/ARI_ADMIN_PASSWORD=$FREEPBX_PASSWD_ESC/" > /tmp/amportal.conf.tmp
        mv /tmp/amportal.conf.tmp /etc/amportal.conf
	cat /etc/asterisk/res_mysql.conf | sed "s/dbpass = $OLDDBPASS/dbpass = $FREEPBX_PASSWD_ESC/" > /tmp/res_mysql.conf.tmp
	mv /tmp/res_mysql.conf.tmp /etc/asterisk/res_mysql.conf
	cat /etc/asterisk/cbmysql.conf | sed "s/password=$OLDCBMYSQL/password=$FREEPBX_PASSWD_ESC/" > /tmp/cbmysql.conf.tmp
	mv /tmp/cbmysql.conf.tmp /etc/asterisk/cbmysql.conf
	cat /etc/asterisk/cdr_mysql.conf | sed "s/password = $OLDCDRMYSQL/password = $FREEPBX_PASSWD_ESC/" > /tmp/cdr_mysql.conf.tmp
	mv /tmp/cdr_mysql.conf.tmp /etc/asterisk/cdr_mysql.conf
	cat /etc/asterisk/manager.conf | sed "s/secret = $OLDAMIPWD/secret = $FREEPBX_PASSWD_ESC/" > /tmp/manager.conf.tmp
        mv /tmp/manager.conf.tmp /etc/asterisk/manager.conf
	for i in /etc/amportal.conf /etc/asterisk/res_mysql.conf /etc/asterisk/cbmysql.conf /etc/asterisk/cdr_mysql.conf ; do
	    chown asterisk.asterisk $i
	    chmod 644 $i
	done

	# Set amiadminpwd in /etc/elastix.conf
	if [ "$AMIPASS" == "yes" ] ; then
                cat $PASSWD_PATH | sed "s/amiadminpwd=$OLDAMIPWD/amiadminpwd=$FREEPBX_PASSWD_ESC/" > /tmp/elastix.conf.tmp
                mv /tmp/elastix.conf.tmp /etc/elastix.conf
        else
                echo "amiadminpwd=$FREEPBX_PASSWD_ESC" >> $PASSWD_PATH
        fi

	# Change ami password in call_center database
	if [ -e "/var/lib/mysql/call_center" ] ; then
        	HOST=`mysql -u root "-p$MYSQL_PASSWD1" call_center -e "SELECT config_value FROM valor_config WHERE config_key='asterisk.asthost'"`
        	HOST=`echo $HOST | sed "s/config_value //"`
        	USER=`mysql -u root "-p$MYSQL_PASSWD1" call_center -e "SELECT config_value FROM valor_config WHERE config_key='asterisk.astuser'"`
        	USER=`echo $USER | sed "s/config_value //"`
        	if [ "$HOST" == "127.0.0.1" -o "$HOST" == "localhost" ] && [ "$USER" == "admin" ] ; then
			mysql -u root "-p$MYSQL_PASSWD1" call_center -e "UPDATE valor_config SET config_value='$FREEPBX_PASSWD_ESC' WHERE config_key='asterisk.astpass'"
        	fi
	fi

	# Set password for Elastix login. Requires sed, md5sum, sqlite3.
	MD5HASH=`echo -n "$FREEPBX_PASSWD1" | md5sum | sed 's/^\(.\{32\}\)  -/\1/'`
	sqlite3 /var/www/db/acl.db "UPDATE acl_user SET md5_password = '$MD5HASH' WHERE name = 'admin'"
	
	# Set password for A2Billing
        WHIRLPOOL=`php -r "echo hash('whirlpool','$FREEPBX_PASSWD1');"`
        echo "UPDATE mya2billing.cc_ui_authen SET pwd_encoded='$WHIRLPOOL' WHERE login='admin';" | mysql -u root "-p$MYSQL_PASSWD1"
	#echo "UPDATE mya2billing.cc_ui_authen SET password = '$FREEPBX_PASSWD1' WHERE login = 'admin';" | mysql -u root -p$MYSQL_PASSWD1
	ret=$?
	if [ $? -ne 0 ]; then
	    echo "Unable to set admin password for A2Billing !"
	    return 1
	fi
	
	# Remove redundant root login from A2Billing
	# echo "DELETE FROM mya2billing.cc_ui_authen WHERE login = 'root';" | mysql -u root -p$MYSQL_PASSWD1
	
	# Set password for VTiger. This assumes the vtigercrm510 database is already created. 
	# This procedure works for VTigerCRM 5.1.0
	echo "UPDATE vtigercrm510.vtiger_users SET user_password = ENCRYPT('$FREEPBX_PASSWD1', CONCAT('\$1\$', SUBSTRING('admin' FROM 1 FOR 2), '\$')), user_hash = md5('$FREEPBX_PASSWD1') WHERE user_name = 'admin'" | mysql -u root "-p$MYSQL_PASSWD1"
	ret=$?
	if [ $? -ne 0 ]; then
	    echo "Unable to set admin password for VTiger !"
	    return 1
	fi

	echo "Restarting amportal..."
	/usr/sbin/amportal restart > /dev/null 2>&1
	echo "All the changes were successfully made!"
	return 0
}

# Perform all tasks that require a running MySQL database
MYSQLPID=`cat "$mypidfile"  2>/dev/null `
if [ -n "$MYSQLPID" ]; then
	elastix_mysql_init
else
	echo "No running MySQL server has been found."
fi
	
exit $?

