#!/usr/bin/php
<?php
/*
  vim: set expandtab tabstop=4 softtabstop=4 shiftwidth=4:
  Codificación: UTF-8
  +----------------------------------------------------------------------+
  | Elastix version 2.0                                                  |
  | http://www.elastix.org                                               |
  +----------------------------------------------------------------------+
  | Copyright (c) 2006 Palosanto Solutions S. A.                         |
  +----------------------------------------------------------------------+
  | Cdla. Nueva Kennedy Calle E 222 y 9na. Este                          |
  | Telfs. 2283-268, 2294-440, 2284-356                                  |
  | Guayaquil - Ecuador                                                  |
  | http://www.palosanto.com                                             |
  +----------------------------------------------------------------------+
  | The contents of this file are subject to the General Public License  |
  | (GPL) Version 2 (the "License"); you may not use this file except in |
  | compliance with the License. You may obtain a copy of the License at |
  | http://www.opensource.org/licenses/gpl-license.php                   |
  |                                                                      |
  | Software distributed under the License is distributed on an "AS IS"  |
  | basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See  |
  | the License for the specific language governing rights and           |
  | limitations under the License.                                       |
  +----------------------------------------------------------------------+
  | The Original Code is: Elastix Open Source.                           |
  | The Initial Developer of the Original Code is PaloSanto Solutions    |
  +----------------------------------------------------------------------+
  $Id: elastix-admin-passwords.php,v 1.1 2007/01/09 23:49:36 alex Exp $
*/
require_once 'Console/Getopt.php';

$g_mysql_running = FALSE;

define('BACKTITLE', 'Elastix password configuration');
define('PASSWD_PATH', '/etc/elastix.conf');
define('REGEXP_VALID_PASSWORD', '/^([a-zA-Z0-9 .&@=_!-]+)$/');

// Parse command-line options
$opt = Console_Getopt::getopt($argv, '', array(
    'init',     // prepare passwords for first-time use
    'change',   // change existing set of passwords
));
if (PEAR::isError($opt)) error_exit($opt->getMessage()."\n");
//validateOptions($opt);
foreach ($opt[0] as $option) switch ($option[0]) {
case '--init':
    exit(action_initPasswords($opt) ? 0 : 1);
case '--change':
    exit(action_changePasswords($opt) ? 0 : 1);
}
error_exit("No action specified (--init or --change)\n");

function error_exit($sMsg, $errorcode = 1)
{
    fwrite(STDERR, $sMsg);
    exit($errorcode);
}

function action_initPasswords($opt)
{
    $bFirstBoot = FALSE;
    $passwords = load_keys();
    if (!isset($passwords['mysqlrootpwd'])) {
        $bFirstBoot = TRUE;

        system("sed -i -e 's/ rd_NO_DM quiet/ rd_NO_DM rhgb quiet/' /boot/grub/grub.conf");

        $odbcini_content = <<<ODBC_INI
[elasuse-connector]
Description = MySQL connection to "elasuse" database
Driver = MySQL
Database = elasuse
Server = localhost
User = asteriskuser
Password = PASSWORD
Port     = 3306
Socket   = /var/lib/mysql/mysql.sock

[asteriskcdrdb-connector]
Description = MySQL connection to "asteriskcdrdb" database
Driver = MySQL
Database = asteriskcdrdb
Server = localhost
User = asteriskuser
Password = PASSWORD
Port     = 3306
Socket   = /var/lib/mysql/mysql.sock

[kamailio-connector]
Description = MySQL connection to "kamailio" database (RW)
Driver = MySQL
Database = kamailio
Server = localhost
User = asteriskuser
Password = PASSWORD
Port     = 3306
Socket   = /var/lib/mysql/mysql.sock
ODBC_INI;
        file_put_contents('/etc/odbc.ini', $odbcini_content);

        check_mysql_running();

        // Prompt for the MySQL password for this system
        if (!elastix_prompt_mysql_passwd()) 
            return FALSE;
    } else {
        print "Password configuration already present.\n";
    }
    
    // Read the MySQL root password for this system
    $passwords = load_keys();
    
    // The scripts placed in /var/spool/elastix-mysqldbscripts should be executed now.
    foreach (glob('/var/spool/elastix-mysqldbscripts/*.sql') as $dbscript) {
        if (file_exists($dbscript)) {
            check_mysql_running();            

            print "Applying MySQL script $dbscript ...\n";
            $output = $retval = NULL;
            exec('mysql -u root '.escapeshellarg('-p'.$passwords['mysqlrootpwd']).' < '.escapeshellarg($dbscript), $output, $retval);
            if ($retval != 0) return FALSE;
            unlink($dbscript);
        }
    }
    
    // Init web passwords if first boot
    if ($bFirstBoot) {
        check_mysql_running();

        // Check if /etc/kamailio/kamailio-mhomed-elastix.cfg exists, setup if not
        if (!file_exists('/etc/kamailio/kamailio-mhomed-elastix.cfg')) {
            print "Setting up Kamailio and rtpproxy configuration...\n";
            system('/usr/sbin/elastix-setup-kamailio-rtpproxy');
        }

        if (!elastix_prompt_web_passwd(FALSE)) return FALSE;

        setup_infomodulesxml();
        setup_wss_keys($passwords['mysqlrootpwd']);
    }

    return TRUE;
}

function action_changePasswords($opt)
{
    if (!file_exists(PASSWD_PATH)) {
        fwrite(STDERR, 'Password configuration /etc/elastix.conf not present.');
        return FALSE;
    }
    
    check_mysql_running();
    
    // Prompt for the MySQL password for this system
    if (!elastix_prompt_mysql_passwd()) return FALSE;
    
    // Prompt for web password
    if (!elastix_prompt_web_passwd(TRUE)) return FALSE;

    return TRUE;
}

function check_mysql_running()
{
    global $g_mysql_running;

    if ($g_mysql_running) return TRUE;
    
    $output = $retval = NULL;
    exec('/sbin/service mysqld status', $output, $retval);
    if ($retval == 0) {
        exec('/sbin/service mysqld start', $output, $retval);
        if ($retval) die("FATAL: unable to start MySQL database server!\n");
    }
    $g_mysql_running = TRUE;
}

function elastix_prompt_mysql_passwd()
{
    $sDialogPurpose =
        "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
    $sMySQL_passwd = array('', '');
    while ($sMySQL_passwd[0] == '') {
        while ($sMySQL_passwd[0] == '') {
            $retstatus = dialog_passwordbox(
                BACKTITLE." (Screen 1 of 4)",
                "$sDialogPurpose Please enter your new MySQL root password:",
                16, 70);
            if ($retstatus['retval'] != 0) return FALSE; 
            $sMySQL_passwd[0] = $retstatus['password'];
            if ($sMySQL_passwd[0] == '') {
                dialog_msgbox(BACKTITLE,
                    'MySQL root password must be nonempty.',
                    7, 40);
            } elseif (!preg_match(REGEXP_VALID_PASSWORD, $sMySQL_passwd[0])) {
                $sMySQL_passwd[0] = '';              
                dialog_msgbox(BACKTITLE,
                    'Admin password may only contain alphanumeric characters, spaces, or the following: .&@=_!-.',
                    7, 40);
            }
        }
        while ($sMySQL_passwd[1] == '') {
            $retstatus = dialog_passwordbox(
                BACKTITLE." (Screen 2 of 4)",
                "Please (re)confirm your new MySQL root password:",
                10, 70);
            if ($retstatus['retval'] != 0) return FALSE;
            $sMySQL_passwd[1] = $retstatus['password'];
        }
        
        if ($sMySQL_passwd[0] != $sMySQL_passwd[1]) {
            dialog_msgbox(BACKTITLE,
                'Password and confirmation do not match!',
                7, 40);
            $sMySQL_passwd[0] = $sMySQL_passwd[1] = '';
        }
    }
    
    if (!set_mysql_root_password($sMySQL_passwd[0])) return FALSE;
    if (!set_cyrus_password($sMySQL_passwd[0])) return FALSE;
    
    print "The password for mysql and cyrus admin were successfully changed!\n";
    sleep(3);

    return TRUE;
}

function set_mysql_root_password($sNewPassword)
{
    // Load old mysql password from file, if it exists
    $sMySQL_oldpasswd = NULL;
    $passwords = load_keys();
    if (isset($passwords['mysqlrootpwd']))
        $sMySQL_oldpasswd = $passwords['mysqlrootpwd'];
    
    // Set new MySQL root password, immediately save on success
    try {
        $db = new PDO('mysql:host=localhost', 'root', $sMySQL_oldpasswd);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // MySQL does not support preparing a GRANT statement
        $quotedPwd = $db->quote($sNewPassword);
        if ($quotedPwd === FALSE) {
            fwrite(STDERR, 'FATAL: failed to quote new MySQL password');
            return FALSE;
        }
        $db->exec("GRANT USAGE ON *.* TO root@localhost IDENTIFIED BY $quotedPwd");
        $db->exec("GRANT USAGE ON *.* TO root IDENTIFIED BY $quotedPwd");
        $db = NULL;

        $passwords['mysqlrootpwd'] = $sNewPassword;
        save_keys($passwords);
    } catch (PDOException $e) {
        fwrite(STDERR, 'FATAL: unable to change mysql root password: '.$e->getMessage()."\n");
        return FALSE;
    }
    
    return TRUE;
}

function set_cyrus_password($sNewPassword)
{
    // Run saslpasswd2 to set the new password
    $r = popen('/usr/sbin/saslpasswd2 -c cyrus -u example.com', 'w');
    if (!is_resource($r)) {
        fwrite(STDERR, "FATAL: failed to open pipe to saslpasswd2\n");
        return FALSE;
    }
    fwrite($r, $sNewPassword);
    $ret = pclose($r);
    if ($ret != 0) {
        fwrite(STDERR, "ERR: unable to set new cyrus password via saslpasswd2\n");
        return FALSE;
    }
    
    // Store just-changed password
    $passwords = load_keys();
    $passwords['cyrususerpwd'] = $sNewPassword;
    save_keys($passwords);
    
    chmod('/etc/sasldb2', 0644);
    
    return TRUE;
}

function elastix_prompt_web_passwd($bRestart)
{
    $sDialogPurpose =
        "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 'superadmin' that will " .
        "be used for: Elastix Web Login.\n\n";

    // Read and set new elastix admin password. 
    $elxPass = array('', '');
    while ($elxPass[0] == '') {
        while ($elxPass[0] == '') {
            $retstatus = dialog_passwordbox(
                BACKTITLE." (Screen 3 of 4)",
                "$sDialogPurpose Please enter your new password for Elastix Web Login 'superadmin':",
                16, 70);
            if ($retstatus['retval'] != 0) return FALSE;
            $elxPass[0] = $retstatus['password'];
            if ($elxPass[0] == '') {
                dialog_msgbox(BACKTITLE,
                    'Admin password must be nonempty.',
                    7, 40);
            } elseif (!preg_match(REGEXP_VALID_PASSWORD, $elxPass[0])) {
                $elxPass[0] = '';
                dialog_msgbox(BACKTITLE,
                    'Admin password may only contain alphanumeric characters, spaces, or the following: .&@=_!<>-.',
                    8, 40);
            } elseif (!isStrongPassword($elxPass[0])) {
                $elxPass[0] = '';
                dialog_msgbox(BACKTITLE,
                    'Admin password must be at least 10 characters and contain at least one uppercase letter, at least one lowercase letter, and at least one digit.',
                    10, 40);
            }
        }
        while ($elxPass[1] == '') {
            $retstatus = dialog_passwordbox(
                BACKTITLE." (Screen 4 of 4)",
                "Please (re)confirm your new password for Elastix Web Login 'superadmin':",
                10, 70);
            if ($retstatus['retval'] != 0) return FALSE;
            $elxPass[1] = $retstatus['password'];
        }
        if ($elxPass[0] != $elxPass[1]) {
            dialog_msgbox(BACKTITLE,
                'Password and confirmation do not match!',
                7, 40);
            $elxPass[0] = $elxPass[1] = '';
        }
    }

    // Open database connection used in several updates
    $passwords = load_keys();
    if (!isset($passwords['mysqlrootpwd'])) {
        fwrite(STDERR, "FATAL: unable to extract MySQL root password\n");
        return FALSE;
    }
    try {
        $db = new PDO('mysql:host=localhost', 'root', $passwords['mysqlrootpwd']);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        fwrite(STDERR, 'FATAL: unable to open database connection: '.$e->getMessage()."\n");
        return FALSE;
    }

    // MySQL does not support preparing a GRANT statement
    $quotedPwd = $db->quote($elxPass[0]);
    if ($quotedPwd === FALSE) {
        fwrite(STDERR, "FATAL: failed to quote new password\n");
        return FALSE;
    }
    
    
    /* The following list defines one element for each known password that needs
     * to be changed to match the password entered above. Each element defines
     * targets on sqlite, mysql, or files. For sqlite, a list of database files
     * is listed, along with the update query and the query parameters. For
     * mysql, the same is done, but the update must indicate the schema name in
     * all of the tables. For files, each file has a PCRE regexp that locates
     * the target line, optionally with a target old password, and the contents
     * of the line that includes the new password. Some cases need additional
     * evaluation and are added dynamically after this declaration. */
    $updateList = array(
        'PBX database password' => array(
            'sqlite'    =>  NULL,
            'mysql'     =>  array(
                array(
                    "GRANT USAGE ON *.* TO asteriskuser@localhost IDENTIFIED BY $quotedPwd",
                    array()
                ),
            ),
            'file'      =>  array(
                // The commented-out files have been replaced with ODBC
                /*
                array(
                    '/etc/asterisk/res_odbc.conf',
                    '^password\s*=>\s*',
                    'password = '.$elxPass[0],
                ),
                // 2014-03-05: cbmysql.conf is missing from Elastix 3 and nobody noticed until now.
                array(
                    '/etc/asterisk/cbmysql.conf',
                    '^password=',
                    'password='.$elxPass[0],
                ),
                array(
                    '/etc/asterisk/cdr_mysql.conf',
                    '^password\s*=\s*',
                    'password = '.$elxPass[0],
                ),
                */
                array(
                    '/var/www/elastixdir/asteriskconf/elastix_pbx.conf',
                    '^DBPASSWORD\s*=\s*',
                    'DBPASSWORD = '.$elxPass[0],
                ),
                array(
                    '/var/www/elastixdir/asteriskconf/elastix_pbx.conf',
                    '^MGPASSWORD\s*=\s*',
                    'MGPASSWORD = '.$elxPass[0],
                ),
                array(
                    '/etc/elastix.conf',
                    '^amiadminpwd\s*=\s*',
                    'amiadminpwd = '.$elxPass[0],
                ),
                array(
                    '/etc/unixODBC/odbc.ini',
                    /*
                    '^Password\s*=\s*',
                    'Password = '.$elxPass[0],
                    */
                    array(
                        'custom', 'change_odbcini_password'
                    ),
                ),
            ),
        ),
        'Asterisk Manager Interface password' => array(
            'sqlite'    =>  NULL,
            'mysql'     =>  NULL,   // Might get CallCenter updates here
            'file'      =>  array(
                array(
                    '/etc/asterisk/manager.conf',
                    array(
                        'custom', 'change_ami_password'
                    ),
                    'secret = '.$elxPass[0],
                ),
            ),
        ),
        'Elastix admin password' => array(
            'sqlite'    =>  NULL,
            'mysql'     =>  array(
                array(
                    'UPDATE elasuse.acl_user SET md5_password = ? WHERE username = ? and id_group = ?',
                    array(md5($elxPass[0]), 'admin', '1'),
                ),
            ),
            'file'      =>  NULL,
        ),
    );

    // List all databases (cannot list specific databases with LIKE)
    $databases = NULL;
    try {
        $sth = $db->prepare('SHOW DATABASES');
        $sth->execute();
        $databases = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
    } catch (PDOException $e) {
        fwrite(STDERR, "FATAL: unable to list databases: ".$e->getMessage()."\n");
        return FALSE;
    }

    foreach ($updateList as $k => $updateItem) {
        print "Updating $k: ";

        // Update all instances of the password in sqlite databases
        if (!is_null($updateItem['sqlite'])) {
            print "sqlite... ";
            foreach ($updateItem['sqlite'] as $updateSqliteItem) {
                try {
                    $dbsqlite = new PDO('sqlite:'.$updateSqliteItem[0]);
                    $dbsqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $sth = $dbsqlite->prepare($updateSqliteItem[1]);
                    $sth->execute($updateSqliteItem[2]);
                    $sth = NULL;
                    $dbsqlite = NULL;
                } catch (PDOException $e) {
                    fwrite(STDERR, "FATAL: unable to update $k: ".$e->getMessage()."\n");
                    return FALSE;
                }
            }
        }
        
        // Update all instances of the password in MySQL
        if (!is_null($updateItem['mysql'])) {
            print "mysql... ";
            foreach ($updateItem['mysql'] as $updateMysqlItem) {
                try {
                    if (strpos($updateMysqlItem[0], 'GRANT') === 0) {
                        // MySQL does not support preparing a GRANT statement
                        $db->exec($updateMysqlItem[0]);
                    } else {
                        $sth = $db->prepare($updateMysqlItem[0]);
                        $sth->execute($updateMysqlItem[1]);
                        $sth = NULL;
                    }
                } catch (PDOException $e) {
                    fwrite(STDERR, "FATAL: unable to update $k: ".$e->getMessage()."\n");
                    return FALSE;
                }
            }
        }
        
        // Update all instances of the password in system files
        if (!is_null($updateItem['file'])) {
            print "files... ";
            foreach ($updateItem['file'] as $fileinfo) {
                if (file_exists($fileinfo[0])) {
                    $content = file($fileinfo[0]);
                    if (is_array($fileinfo[1])) {
                        switch ($fileinfo[1][0]) {
                        case 'custom':
                            if (function_exists($fileinfo[1][1]))
                                $fileinfo[1][1]($content, $elxPass[0]);
                            break;
                        }
                    } else {
                        for ($i = 0; $i < count($content); $i++) {
                            if (preg_match("/".$fileinfo[1]."/", rtrim($content[$i], "\r\n"))) {
                                $content[$i] = $fileinfo[2]."\n";
                                break;
                            }
                        }
                    }
                    file_put_contents($fileinfo[0], $content);
                }
            }
        }
        
        print " updated\n";
    }

    if ($bRestart) {
        $ret = NULL;
    
        // Do a full Asterisk restart, since database passwords everywhere have changed
        print "Restarting asterisk...\n";
        system('/sbin/service asterisk restart > /dev/null 2>&1', $ret);
        if ($ret != 0) fwrite(STDERR, "ERR: failed to restart asterisk: $ret\n");
        
        // Ditto for Kamailio
        print "Restarting kamailio...\n";
        system('/sbin/service kamailio restart > /dev/null 2>&1', $ret);
        if ($ret != 0) fwrite(STDERR, "ERR: failed to restart kamailio: $ret\n");
    }

    return TRUE;
}

function isStrongPassword($password)
{
    return (strlen($password) >= 10 && preg_match('/[a-z]+/', $password) 
        && preg_match('/[A-Z]+/', $password) && preg_match('/[0-9]+/', $password));
}

// Change password, ONLY for admin section
function change_ami_password(&$content, $sNewPassword)
{
    $targets = array('admin');
    change_ini_password($content, $targets, 'secret', $sNewPassword);
}

// Change password, ONLY FOR known Elastix sections
function change_odbcini_password(&$content, $sNewPassword)
{
    $targets = array(
        'elasuse-connector',
        'asteriskcdrdb-connector',
        'kamailio-connector');
    change_ini_password($content, $targets, 'Password', $sNewPassword);
}

// Change key value for specified target sections in INI-style file
function change_ini_password(&$content, $targets, $key, $sNewPassword)
{
    $bTarget = FALSE;
    $regexp = "/^$key\\s*=\\s*/";
    for ($i = 0; $i < count($content); $i++) {
        $regs = NULL;
        if (preg_match('/^\[([[:alnum:]_-]+)\]/', $content[$i], $regs)) {
            $bTarget = in_array($regs[1], $targets);
        } elseif ($bTarget && preg_match($regexp, $content[$i])) {
            $content[$i] = "$key = $sNewPassword\n";
        }
    }
}

function dialog_msgbox($backtitle, $msgbox, $height, $width)
{
    $height = (int)$height;
    $width = (int)$width;
    passthru('/usr/bin/dialog'.
        ' --backtitle '.escapeshellarg($backtitle).
        ' --msgbox '.escapeshellarg($msgbox).
        " $height $width");
}

function dialog_passwordbox($backtitle, $msgbox, $height, $width)
{
    global $option;
    $height = (int)$height;
    $width = (int)$width;

    $pipes = NULL;
    $pipespec = array(
        0 => STDIN,
        1 => STDOUT,
        2 => STDERR,
        3 => array('pipe', 'w'));
        
    if ($option[0] == "--init"){
       $cncl=' --no-cancel';
    }
     
    $r = @proc_open('/usr/bin/dialog'.
        $cncl.
        ' --output-fd 3'.
        ' --backtitle '.escapeshellarg($backtitle).
        ' --insecure --passwordbox '.escapeshellarg($msgbox).
        " $height $width",
        $pipespec,
        $pipes);
    if (is_resource($r)) {
        $password = stream_get_contents($pipes[3]);
        fclose($pipes[3]);
        return array('retval' => proc_close($r), 'password' => $password);
    } else {
        return NULL;
    }
}

// Need custom function to load conf file, odd characters choke parse_ini_file()
function load_keys()
{
    $keys = array();
    if (file_exists(PASSWD_PATH)) foreach (file(PASSWD_PATH) as $s) {
        $s = rtrim($s, "\r\n");
        $regs = NULL;
        if (preg_match('/^(\w+)=(.*)$/', $s, $regs))
            $keys[$regs[1]] = $regs[2];
    }
    return $keys;
}

function save_keys($keys)
{
    $s = '';
    foreach ($keys as $k => $v) $s.= "$k=$v\n";
    file_put_contents(PASSWD_PATH, $s);
    chmod(PASSWD_PATH, 0600);
    chown(PASSWD_PATH, 'asterisk');
    chgrp(PASSWD_PATH, 'asterisk');
}

/* Apply the XML definitions for module menus. This assumes each RPM package has
 * created a directory that follows the name convention of
 * /var/spool/elastix-infomodulesxml/elastix-MODNAME-xxx/infomodules/ where all
 * of the XML definitions are stored. 
 */
function setup_infomodulesxml()
{
    foreach (glob('/var/spool/elastix-infomodulesxml/*') as $modulepath) {
        $module_part_list = explode('-', basename($modulepath));
        if (!is_dir($modulepath) || count($module_part_list) < 2) {
            fwrite(STDERR, "WARN: skipping invalid directory entry $modulepath\n");
            continue;
        }        
        
        print "\nInstalling web menu for {$module_part_list[1]}...\n";
        $abs_path = $modulepath.'/infomodules'; $retval = NULL;
        system("/usr/bin/elastix-menumerge $abs_path", $retval);
        if ($retval == 0) {
            array_map('unlink', glob($abs_path.'/*'));
            rmdir($abs_path);
        }
    }
}

/* Setup using WSS as a SIP transport for Asterisk websockets. */
function setup_wss_keys($passwd)
{
    // Copy keys into locations readable by Asterisk
    print "WSS switch: setting up key files...\n";
    $keylist = array(
        array(
            '/etc/pki/tls/private/localhost.key',
            '/etc/pki/tls/private/localhost_asterisk.key'
        ),
        array(
            '/etc/pki/tls/certs/localhost.crt',
            '/etc/pki/tls/certs/localhost_asterisk.crt',
        ),
    );
    $success = TRUE;
    foreach ($keylist as $keytuple) {
    	if (!file_exists($keytuple[0])) {
            fwrite(STDERR, "\nERROR: Key file {$keytuple[0]} not found.\n");
            $success = FALSE;
    		break;
    	}
        if (!copy($keytuple[0], $keytuple[1])) {
            fwrite(STDERR, "\nERROR: Failed to copy key file {$keytuple[0]} to {$keytuple[1]} .\n");
            $success = FALSE;
            break;
        }
        print "\tCopied key file {$keytuple[0]} to {$keytuple[1]} .\n";
    }

    // tlsenable switch is not required since wss is now handled by kamailio
/*    
    // Switch tlsenable to yes in /etc/asterisk/http.conf
    if ($success) {
        print "WSS switch: switching tlsenable in Asterisk configuration...\n";
        $conf = '/etc/asterisk/http.conf';
        $s = file_get_contents($conf);
        if (($s === FALSE) || (FALSE === file_put_contents($conf,
            str_replace('tlsenable=no', 'tlsenable=yes', $s)))) {
            fwrite(STDERR, "\nERROR: Failed to switch tlsenable in $conf\n");
            $success = FALSE;
        }
    }
*/
    // Update webservice SIP URI
    if ($success) try {
        print "WSS switch: switching SIP URI to WSS...\n";
        $conn = new PDO('mysql:dbname=elasuse;host=localhost', 'root', $passwd);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->exec('UPDATE elx_chat_config SET property_val = "wss" WHERE property_name = "type_connection"');
    } catch(PDOException $e) {
        fwrite(STDERR, "\nERROR: ".$e->getMessage()."\n");
        $success = FALSE;
    }
    
    print ($success 
        ? "WSS switch completed!\n"
        : "Failed to switch to WSS, trying to use WS for SIP websocket.\n");
}
?>
