#!/bin/bash

# Rocky Linux release 10.0 (Red Quartz)
# kernels 6.12.0-55.41.1.el10_0.x86_64
# Redis server v=6.2.7
# asteriskver=13.38.3
# libpriver=1.6.1
# asterccver=4.2
# dahdiver=3.4.0-rc1+3.4.0-rc1-rocky10
# lamever=3.100
# mpg123ver=1.13.4
# nginxver=1.20.2
# phpver=7.4.33
# mariadbver=10.11.11
# ioncubever=7.4

function kernel_upgrade(){
    kernel_reminder_file="/tmp/kernel_update_reminder"
    if [ -f "$kernel_reminder_file" ]; then
        echo -e "\e[32mplease reboot your server and run this script again\e[m\n"
        exit 1
    fi

    if [[ $UID -ne 0 ]]; then
        echo "this script requires root privileges" >&2
        exit 1
    fi

    if [[ ! -e /etc/redhat-release ]]; then
        echo "not an EL distro"
        exit 1
    fi

    if [[ $RELEASEVER -ne 10 ]]; then
        echo "unsupported OS version, need to be 10.X"
        exit 1
    fi

    kernel_update_info=$(dnf check-update kernel)
    kernel_update_version=$(echo "$kernel_update_info" | grep -oP 'kernel\.x86_64\s+\K\S+')

    dnf -y update 
    dnf -y install make
    dnf -y update kernel

    if [ -n "$kernel_update_version" ] && [ "$(rpm -q kernel | wc -l)" -gt 1 ]; then
        touch "$kernel_reminder_file"
        if ! grep -q "rm -f $kernel_reminder_file" "/etc/rc.local"; then
            chmod +x /etc/rc.d/rc.local
            echo "rm -f $kernel_reminder_file" >> /etc/rc.local
        fi
        echo -e "\e[32mplease reboot your server and run this script again\e[m\n"
        exit 1
    fi

    uname_info=$(uname -a)
    current_kernel_version=$(echo "$uname_info" | awk '{print $3}')

    if [ -n "$kernel_update_version" ] && [ -n "$current_kernel_version" ] && [ "$kernel_update_version" != "$current_kernel_version" ]; then
        echo -e "\e[31mKernel update failed, please update the kernel\e[m\n"
        exit 1
    fi

    dnf -y install kernel-headers
    dnf -y install kernel-devel-$(uname -r)
    dnf -y install tar
}

function dahdi_install() {
    echo -e "\e[32mStarting Install DAHDI\e[m"

    systemctl restart dahdi
    status=$(systemctl is-active dahdi)

    if [ "$status" != "active" ]; then
        dnf -y install libtool* autoconf* automake* autoconf initscripts
    
        cd /usr/src
        if [ ! -e ./dahdi-linux-complete-$dahdiver.tar.gz ]; then
            wget $downloadmirror/dahdi-linux-complete-$dahdiver.tar.gz
            #if [ ! -e ./dahdi-linux-complete-$dahdiver.tar.gz ]; then
            #    wget http://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/releases/dahdi-linux-complete-$dahdiver.tar.gz
            #fi
        fi

        tar zxf dahdi-linux-complete-$dahdiver.tar.gz

        if [ $? != 0 ]; then
            echo -e "fatal: dont have valid dahdi tar package\n"
            exit 1
        fi

        cd dahdi-linux-complete-$dahdiver
        make clean
        make
        make install
        make install-config
        /usr/sbin/dahdi_genconf
        echo "blacklist netjet" >> /etc/modprobe.d/dahdi-blacklist.conf
        echo "/usr/lib" | sudo tee /etc/ld.so.conf.d/tonezone.conf
        ldconfig
        systemctl daemon-reload
        cp /etc/dahdi/system.conf.sample /etc/dahdi/system.conf
        cp /etc/dahdi/assigned-spans.conf.sample /etc/dahdi/assigned-spans.conf
        systemctl start dahdi
    fi

    echo -e "\e[32mDAHDI Install OK!\e[m"
}

function newRepo_install(){
    cd /usr/src

    dnf install epel-release dnf-plugins-core -y
    dnf config-manager --set-enabled crb

    # rpm --import https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-$RELEASEVER
    # yum --assumeyes install https://dl.fedoraproject.org/pub/epel/epel-release-latest-$RELEASEVER.noarch.rpm
    # sed -i "s/mirrorlist/#mirrorlist/" /etc/yum.repos.d/ius.repo
    # sed -i "s/#baseurl/baseurl/" /etc/yum.repos.d/ius.repo

    echo -e "\033[32m Epel repo configured \033[0m"
}

function update_system_config(){
    setenforce 0
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
    echo -e "\033[32m Stop SELINUX OK! \033[0m"
    systemctl stop firewalld.service
    systemctl disable firewalld.service
    echo -e "\033[32m Stop Firewalld OK! \033[0m"
    if ! grep -q "export LANG=en_US.UTF-8" "/etc/profile"; then
        echo "export LANG=en_US.UTF-8" >> /etc/profile
    fi
    if ! grep -q "export LC_ALL=en_US.UTF-8" "/etc/profile"; then
        echo "export LC_ALL=en_US.UTF-8" >> /etc/profile
    fi
    if ! grep -q "/usr/local/bin" "/etc/profile"; then
        echo "PATH=\$PATH:/usr/local/bin" >> /etc/profile
    fi
    source /etc/profile
    echo /usr/local/lib64/ > /etc/ld.so.conf.d/local.lib64.conf
    ldconfig


    if ! grep -q /usr/local/bin ~/.bashrc; then
        echo "export PATH=/usr/local/bin:$PATH" >> ~/.bashrc
        export PATH=/usr/local/bin:$PATH
    fi
    echo -e "\033[32m Language Change Success! \033[0m"
    dnf -y install wget bash git vim bash-completion.noarch mlocate expect*
    echo -e "\033[32m ===================================================================== \033[0m"
}

function yum_install(){
    dnf -y remove php*
    dnf -y remove asterisk
    dnf -y remove mariadb*

    # rpm --import https://supplychain.mariadb.com/MariaDB-Server-GPG-KEY
    # curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup | sudo bash -s -- --mariadb-server-version="mariadb-10.5"
    dnf -y install mariadb-server

    dnf -y install cpan crontabs glibc gcc-c++ newt newt-devel ncurses ncurses-devel libtool libxml2-devel subversion flex libstdc++-devel libstdc++ unzip sharutils openssl-devel make postfix bzip2 net-tools
    dnf module enable redis:remi-8.4 -y
    dnf install -y redis postfie
    dnf -y update kernel-headers
    dnf -y install kernel-headers gcc perl
    dnf -y install kernel-devel autoconf automake libtool perl-Config-Tiny
    dnf -y install rsyslog sysstat
    dnf -y install ghostscript
    dnf -y install libnsl

    # wget -O "/etc/rc.d/init.d/functions"  "$downloadmirror/rocky9-init-functions"

    systemctl enable mariadb
    systemctl enable crond
    systemctl start crond
}

function php_install(){
    echo -e "\e[32mStarting Install PHP-Fpm\e[m"
    if [ -e /etc/php.ini.rpmnew -a ! -e /etc/php.ini ]; then
        cp /etc/php.ini.rpmnew /etc/php.ini
    fi

    dnf -y remove php*
    dnf -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-10.noarch.rpm
    dnf -y install https://rpms.remirepo.net/enterprise/remi-release-10.rpm
    dnf -y install yum-utils
    dnf -y module reset php
    dnf -y module install php:remi-7.4
    dnf -y install php-fpm php-cli pcre2-devel php-mysqlnd sox php-gd php-mbstring php-pecl-redis php-soap php-xml

    wget $downloadmirror/ioncube/ioncube_loader_lin_7.4.so -O /usr/lib64/php/modules/ioncube_loader_lin_7.4.so

    sed -i "s/short_open_tag = Off/short_open_tag = On\nzend_extension = \/usr\/lib64\/php\/modules\/ioncube_loader_lin_7.4.so/" /etc/php.ini 
    sed -i "s/memory_limit = 16M /memory_limit = 128M /" /etc/php.ini 
    sed -i "s/upload_max_filesize = 2M/upload_max_filesize = 20M /" /etc/php.ini 
    sed -i "s/post_max_size = 8M/post_max_size = 20M/" /etc/php.ini
    sed -i '/^error_reporting/c error_reporting = E_ALL & ~E_DEPRECATED' /etc/php.ini
    sed -i "s/user = .*/user = asterisk/" /etc/php-fpm.d/www.conf
    sed -i "s/group = .*/group = asterisk/" /etc/php-fpm.d/www.conf
    sed -i "s/listen = \/run\/php-fpm\/www.sock/listen = 127.0.0.1\:9000/" /etc/php-fpm.d/www.conf

    systemctl enable php-fpm

    echo -e "\e[32mPHP-Fpm Install OK!\e[m"
}


function mpg123_install(){
    echo -e "\e[32mStarting Install MPG123\e[m"
    cd /usr/src
    if [ ! -e ./mpg123-$mpg123ver.tar.bz2 ]; then
        #wget http://sourceforge.net/projects/mpg123/files/mpg123/$mpg123ver/mpg123-$mpg123ver.tar.bz2/download -O mpg123-$mpg123ver.tar.bz2
        wget $downloadmirror/mpg123-$mpg123ver.tar.bz2
    fi

    tar jxf mpg123-$mpg123ver.tar.bz2
    cd mpg123-$mpg123ver
    ./configure
    make
    make install
    echo -e "\e[32mMPG123 Install OK!\e[m"
}

function nginx_install(){
    echo -e "\e[32mStarting install nginx\e[m"
    #service httpd stop
    #chkconfig httpd off
    cd /usr/src
    if [ ! -e ./nginx-$nginxver.tar.gz ]; then
        wget $downloadmirror/nginx-$nginxver.tar.gz
    fi

    if [ ! -e ./pcre-8.45.tar.gz ]; then
        wget $downloadmirror/pcre-8.45.tar.gz
        tar zxf pcre-8.45.tar.gz
    fi

    tar zxf nginx-$nginxver.tar.gz
    if [ $? != 0 ]; then
        echo -e "fatal: dont have valid nginx tar package\n"
        exit 1
    fi

    if [ ! -e ./nginx-push-stream-module.tar.gz ]; then
        wget $downloadmirror/nginx-push-stream-module.tar.gz
    fi
    
    tar zxf nginx-push-stream-module.tar.gz
    if [ $? != 0 ]; then
        echo -e "fatal: dont have valid nginx push tar package\n"
        exit 1
    fi

    cd nginx-$nginxver
    ./configure --add-module=/usr/src/nginx-push-stream-module --with-http_ssl_module --with-pcre=/usr/src/pcre-8.45 --user=asterisk --group=asterisk
    make
    make install
    echo -e "\e[32mNginx Install OK!\e[m"
}

function asterisk_install() {
    echo -e "\e[32mStarting Install Asterisk\e[m"
    cd /usr/src

    #wget https://dl.rockylinux.org/pub/rocky/9/devel/x86_64/os/Packages/j/jansson-devel-2.14-1.el9.x86_64.rpm
    #dnf -y localinstall  jansson-devel-2.14-1.el9.x86_64.rpm
    dnf group -y install "Development Tools"
    dnf install -y binutils-devel bluez-libs-devel codec2 codec2-devel dmidecode freetds-devel gsm-devel gtk2-devel jansson-devel libcurl-devel libedit-devel libical-devel libmcrypt-devel libogg-devel libpq-devel libresample-devel libsrtp-devel libtool-ltdl-devel libuuid-devel libvorbis-devel libxslt-devel lua-devel neon-devel net-snmp-devel openldap-devel popt-devel portaudio-devel speex-devel sqlite sqlite-devel unixODBC-devel uuid-devel xmlstarlet
    dnf install -y libsamplerate-devel
    dnf install -y libmcrypt
    dnf install -y mariadb-devel postgresql-devel libcurl-devel unixODBC-devel sqlite-devel libedit-devel jansson-devel gsm-devel speex-devel portaudio-devel gtk2-devel

    useradd -u 500 -c "Asterisk PBX" -d /var/lib/asterisk asterisk
    #Define a user called asterisk.
    mkdir /var/run/asterisk /var/log/asterisk /var/spool/asterisk /var/lib/asterisk
    chown -R asterisk:asterisk /var/run/asterisk /var/log/asterisk /var/lib/php /var/lib/asterisk /var/spool/asterisk/
    #Change the owner of this file to asterisk.
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config 
    setenforce 0
    #shutdown selinux

    # if [ ! -e ./iksemel-devel-1.4-2.el7.aarch64.rpm ]; then
    #     wget http://mirror.centos.org/altarch/7/extras/aarch64/Packages/iksemel-devel-1.4-2.el7.aarch64.rpm
    # fi

    if [ ! -e /tmp/jansson-2.12.tar.bz2 ]; then
        wget $downloadmirror/jansson-2.12.tar.bz2 -P /tmp
    fi

    if [ ! -e ./asterisk-$asteriskver.tar.gz ]; then
        #wget http://downloads.asterisk.org/pub/telephony/asterisk/old-releases/asterisk-$asteriskver.tar.gz
        # https://downloads.asterisk.org/pub/telephony/asterisk/releases/asterisk-11.25.3.tar.gz
        wget $downloadmirror/asterisk-$asteriskver.tar.gz
    fi
    tar zxf asterisk-$asteriskver.tar.gz
    if [ $? != 0 ]; then
        echo "fatal: dont have valid asterisk tar package"
        exit 1
    fi
    
    cd asterisk-$asteriskver
    ./contrib/scripts/install_prereq install

    ./configure --disable-xmldoc --with-jansson-bundled

    wget $downloadmirror/asterisk-$asteriskver-menuselect.makeopts -O menuselect.makeopts
    #make menuselect

    make clean
    make
    make install
    make samples
    #This command will  install the default configuration files.
    #make progdocs
    #This command will create documentation using the doxygen software from comments placed within the source code by the developers. 
    make config

    # if [[ ! -e /usr/lib/asterisk/modules/codec_g729a.so ]]; then
    #     wget /mnt/www/download2.astercc.org/httpdocs/codec_g729a-13.0_3.1.10-x86_64/codec_g729a.so -P /usr/lib/asterisk/modules
    #     chmod 755 /usr/lib/asterisk/modules/codec_g729a.so
    # fi

cat > /usr/lib/systemd/system/asterisk.service << EOF
[Unit]
Description=Asterisk PBX And Telephony Daemon
After=network.target

[Service]
Environment=HOME=/var/lib/asterisk
WorkingDirectory=/var/lib/asterisk
ExecStart=/usr/sbin/asterisk -f -C /etc/asterisk/asterisk.conf
ExecStop=/usr/sbin/asterisk -rx 'core stop now'
ExecReload=/usr/sbin/asterisk -rx 'core reload'
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

    #This command will install the startup scripts and configure the system (through the use of the chkconfig command) to execute Asterisk automatically at startup.
    sed -i "s/#AST_USER/AST_USER/" /etc/init.d/asterisk
    sed -i "s/#AST_GROUP/AST_GROUP/" /etc/init.d/asterisk
    sed -i 's/;enable=yes/enable=no/' /etc/asterisk/cdr.conf

    # set AMI user
cat > /etc/asterisk/manager.conf << EOF
[general]
enabled = yes
port = 5038
bindaddr = 0.0.0.0
displayconnects=no

[asterccuser]
secret = asterccsecret
deny=0.0.0.0/0.0.0.0
permit=127.0.0.1/255.255.255.0
read = system,call,agent
write = all
EOF

    systemctl daemon-reload
    systemctl restart asterisk
    systemctl enable asterisk
    systemctl restart systemd-udevd

    echo -e "\e[32mAsterisk Install OK!\e[m"
}

function sngrep_install() {
    echo -e "\e[32mStarting Install sngrep\e[m"
    cd /usr/src
    if [ ! -e "./sngrep-1.8.3.tar.gz" ]; then
        wget https://github.com/irontec/sngrep/releases/download/v1.8.3/sngrep-1.8.3.tar.gz
    fi

    tar zxf sngrep-1.8.3.tar.gz
    cd sngrep-1.8.3
    dnf -y install ncurses-devel make libpcap-devel pcre2-devel openssl-devel git gcc autoconf automake
    ./bootstrap.sh
    ./configure
    make && make install

    echo -e "\033[32m sngrep Install OK! \033[0m"
    echo -e "\033[32m ===================================================================== \033[0m"  
}

function lame_install(){
    echo -e "\e[32mStarting Install Lame for mp3 monitor\e[m"
    cd /usr/src
    if [ ! -e "./lame-3.100.tar.gz" ]; then
        wget https://jaist.dl.sourceforge.net/project/lame/lame/3.100/lame-3.100.tar.gz
    fi
    tar zxf lame-3.100.tar.gz
    if [ $? != 0 ]; then
        echo -e "fatal: dont have valid lame tar package\n"
        exit 1
    fi
    cd lame-3.100
    ./configure && make && make install
    if [ $? != 0 ]; then
        echo -e "fatal: dont have valid lame tar package\n"
        exit 1
    fi

    ln -s /usr/local/bin/lame /bin/lame

    echo -e "\e[32mLame Install OK!\e[m"
}

function libpri_install() {
    echo -e "\e[32mStarting Install LibPRI\e[m"
    cd /usr/src
    if [ ! -e ./libpri-$libpriver.tar.gz ]; then
        #wget http://downloads.asterisk.org/pub/telephony/libpri/releases/libpri-$libpriver.tar.gz
        wget $downloadmirror/libpri-$libpriver.tar.gz
    fi
    tar zxf libpri-$libpriver.tar.gz
    if [ $? != 0 ]; then
        echo -e "fatal: dont have valid libpri tar package\n"
        exit 1
    fi

    cd libpri-$libpriver
    make
    make install
    echo -e "\e[32mLibPRI Install OK!\e[m"
}

function logrotate_install(){
cat > /etc/logrotate.d/astercc.logrotate << EOF
/opt/asterisk/scripts/astercc/*.log {
    daily
    rotate 10
    copytruncate
    delaycompress
    compress
    notifempty
    missingok
}
EOF
}

function nginx_conf_install(){
    mkdir /var/www/html/asterCC/http-log -p
cat >  /usr/local/nginx/conf/nginx.conf << EOF
#user  nobody;
worker_processes  1;
worker_rlimit_nofile 655350;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        /run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                      '\$status \$body_bytes_sent "\$http_referer" '
                      '"\$http_user_agent" "\$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;

    push_stream_store_messages on;
    push_stream_shared_memory_size  256M;
    push_stream_message_ttl  15m;

    #gzip  on;
    server
    {
        listen       80 default;
        client_max_body_size 20M;
        index index.html index.htm index.php;
        root  /var/www/html/asterCC/app/webroot;

        location / {
          index index.php;

          if (-f \$request_filename) {
            break;
          }
          if (!-f \$request_filename) {
            rewrite ^/(.+)\$ /index.php?url=\$1 last;
            break;
          }
  
            location  /agentindesks/pushagent {
                push_stream_publisher admin;
                push_stream_channels_path    \$arg_channel;
            }

            location ~ /agentindesks/agentpull/(.*) {
                push_stream_subscriber      long-polling;
                push_stream_channels_path    \$1;
                push_stream_message_template                 ~text~;
                push_stream_longpolling_connection_ttl        60s;	
            }

            location  /publicapi/pushagent {
                push_stream_publisher admin;
                push_stream_channels_path    \$arg_channel;
            }

            location ~ /publicapi/agentpull/(.*) {
                push_stream_subscriber      long-polling;
                push_stream_channels_path    \$1;
                push_stream_message_template         "{\"text\":\"~text~\",\"tag\":~tag~,\"time\":\"~time~\"}";
                push_stream_longpolling_connection_ttl        60s;
                push_stream_last_received_message_tag       \$arg_etag;
                push_stream_last_received_message_time      \$arg_since;
            }
            
            location  /systemevents/pushagent {
                push_stream_publisher admin;
                push_stream_channels_path    \$arg_channel;
            }

            location ~ /systemevents/agentpull/(.*) {
                push_stream_subscriber      long-polling;
                push_stream_channels_path    \$1;
                push_stream_message_template                 ~text~;
                push_stream_longpolling_connection_ttl        60s;
            }
        }

        location ~ /\.ht {
          deny all;
        }
        location ~ .*\.(php|php5)?\$
        {
          fastcgi_pass  127.0.0.1:9000;
          fastcgi_index index.php;
          include fastcgi_params;
          fastcgi_param  SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
          fastcgi_connect_timeout 60;
          fastcgi_send_timeout 180;
          fastcgi_read_timeout 180;
          fastcgi_buffer_size 128k;
          fastcgi_buffers 4 256k;
          fastcgi_busy_buffers_size 256k;
          fastcgi_temp_file_write_size 256k;
          fastcgi_intercept_errors on;
        }

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|wav)$
        {
          access_log   off;
          expires 15d;
        }

        location ~ .*\.(js|css)?$
        {
          expires 1d;
        }

        access_log /var/www/html/asterCC/http-log/access.log main;
    }
}
EOF
    #RELEASEVER=$(rpm --eval %rhel)


cat > /lib/systemd/system/nginx.service << EOF
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable nginx 
    systemctl start nginx 


echo -ne "
* soft nofile 655360
* hard nofile 655360
" >> /etc/security/limits.conf

echo "fs.file-max = 1572775" >> /etc/sysctl.conf
echo "net.ipv4.ip_local_port_range = 1024 65000" >> /etc/sysctl.conf
echo "net.ipv4.tcp_fin_timeout = 45" >> /etc/sysctl.conf
echo "vm.dirty_ratio=10" >> /etc/sysctl.conf
echo "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
#echo "net.ipv4.tcp_tw_recycle = 1" >> /etc/sysctl.conf

sysctl -p
}

function astercc_install() {
    systemctl restart asterisk

    echo -e "\e[32mStarting Install AsterCC\e[m"
    cd /usr/src
    if [ ! -e ./astercc-$asterccver.tar.gz ]; then
        wget $downloadmirror/astercc-$asterccver.tar.gz -t 5
    fi

    tar zxf astercc-$asterccver.tar.gz
    if [ $? != 0 ]; then
        echo "dont have valid astercc tar package, try run this script again or download astercc-$asterccver.tar.gz to /usr/src manually then run this script again"
        exit 1
    fi

    cd astercc-$asterccver
    chmod +x install.sh
    . /tmp/.mysql_root_pw.$$

    ./install.sh -dbu=root -dbpw=$mysql_root_pw -amiu=$amiu -amipw=$amipw -allbydefault

    sed -i "s/preload =>  chan_local.so/;;; preload =>  chan_local.so/" /etc/asterisk/modules.conf
    sed -i "s/load => app_addon_sql_mysql.so/;;; load => app_addon_sql_mysql.so/" /etc/asterisk/modules.conf
    sed -i "s/load => chan_agent.so/;;; load => chan_agent.so/" /etc/asterisk/modules.conf
    sed -i "s/load => chan_bridge.so/;;; load => chan_bridge.so/" /etc/asterisk/modules.conf
    sed -i "s/load => format_sln16.so/;;; load => format_sln16.so/" /etc/asterisk/modules.conf
    sed -i "s/;;; load => app_mp3.so/load => app_mp3.so/" /etc/asterisk/modules.conf
    sed -i "s/load => format_mp3.so/;;; load => format_mp3.so/" /etc/asterisk/modules.conf
    if ! grep -q "load => func_periodic_hook.so" "/etc/asterisk/modules.conf"; then
        echo "load => func_periodic_hook.so" >> /etc/asterisk/modules.conf
    fi

    sed -i "s/ASTERCCCSERVER = localhost:4577/ASTERCCCSERVER = 127.0.0.1:4577/" /etc/asterisk/extensions.conf
    asterisk -rx "dialplan reload"

    echo -e "\e[32mAsterCC Commercial Install OK!\e[m"
}

function set_ami(){
    while true;do
        echo -e "\e[32mplease give an AMI user\e[m";
        read amiu;
        if [ "X${amiu}" != "X" ]; then
            break;
        fi
    done

    while true;do
        echo -e "\e[32mplease give an AMI secret\e[m";
        read amipw;
        if [ "X${amipw}" != "X" ]; then
            break;
        fi
    done
cat > /etc/asterisk/manager.conf << EOF
[general]
enabled = yes
port = 5038
bindaddr = 0.0.0.0
displayconnects=no

[$amiu]
secret = $amipw
deny=0.0.0.0/0.0.0.0
permit=127.0.0.1/255.255.255.0
read = system,call,agent
write = all
EOF

    asterisk -rx "manager reload"

    echo amiu=$amiu >> /tmp/.mysql_root_pw.$$
    echo amipw=$amipw >> /tmp/.mysql_root_pw.$$
}

function get_mysql_passwd(){
    systemctl start mariadb

    while true;do
        echo -e "\e[32mplease enter your mysql root passwd\e[m";
        read mysql_passwd;
        # make sure it's not a empty passwd
        if [ "X${mysql_passwd}" != "X" ]; then
            mysqladmin -uroot -p$mysql_passwd password $mysql_passwd  >/dev/null 2>&1 # try empty passwd
            if [ $? == 0  ]; then
                mysql -uroot -p$mysql_passwd -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' IDENTIFIED by'$mysql_passwd';"
                mysql -uroot -pastercc -e "FLUSH PRIVILEGES"
                break;
            fi

            mysqladmin password "$mysql_passwd" 
            #mysql -uroot -p$mysql_passwd -e "SET PASSWORD FOR 'root'@'127.0.0.1' = PASSWORD('$mysql_passwd');"
            mysql -uroot -p$mysql_passwd -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' IDENTIFIED by'$mysql_passwd';"
            mysql -uroot -pastercc -e "FLUSH PRIVILEGES"
            if [ $? == 0  ]; then
                break;
            fi

            echo -e "\e[32minvalid password,please try again\e[m"
        fi
    done
cat > /etc/my.cnf << EOF
[mysql]
no-auto-rehash

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
#old_passwords=1

# Disabling symbolic-links is recommended to prevent assorted security risks;
# to do so, uncomment this line:
# symbolic-links=0
skip-name-resolve
skip-external-locking
### table_open_cache = 1024

open_files_limit = 10240
back_log = 600

## MyISAM Engine
key_buffer_size = 384M
myisam_sort_buffer_size         = 128M  #index buffer size for creating/altering indexes
myisam_max_sort_file_size       = 256M  #max file size for tmp table when creating/alering indexes
myisam_repair_threads           = 4     #thread quantity when running repairs
myisam_recover                  = BACKUP        #repair mode, recommend BACKUP

## Connections
max_connections = 4096
max_connect_errors              = 8192  #default: 10
concurrent_insert               = 2     #default: 1, 2: enable insert for all instances
connect_timeout                 = 30    #default -5.1.22: 5, +5.1.22: 10
max_allowed_packet              = 64M   #max size of incoming data to allow

## Thread settings
### thread_concurrency = 16
#
###thread_cache_size               = 300 #recommend 5% of max_connections
# 1G memory: 8
# 2G memory: 16
# 3G memory: 32
# 4G memory: +

## Per-Thread Buffers * (max_connections) = total per-thread mem usage
thread_stack                    = 256K    #default: 32bit: 192K, 64bit: 256K
sort_buffer_size                = 512K    #default: 2M, larger may cause perf issues
read_buffer_size                = 1M    #default: 128K, change in increments of 4K
read_rnd_buffer_size            = 512K    #default: 256K
join_buffer_size                = 512K    #default: 128K
binlog_cache_size               = 64K     #default: 32K, size of buffer to hold TX queries


query_cache_size = 64M
query_cache_limit = 4M

max_heap_table_size = 256M
bulk_insert_buffer_size = 64M
tmp_table_size = 256M

wait_timeout = 180
### long_query_time=1
### log-slow-queries=/var/log/mysqld_slow.log

innodb_file_per_table = 1
innodb_table_locks = 0
innodb_log_buffer_size          = 128M  #global buffer
innodb_lock_wait_timeout        = 60
innodb_thread_concurrency       = ##CPUCORE##    #recommend 2x core quantity
innodb_commit_concurrency       = ##CPUCORE##    #recommend 4x num disks
skip-innodb-doublewrite
innodb_flush_log_at_trx_commit  = 2
expire_logs_days = 5
### innodb_buffer_pool_size = 1024M         #recommend 70-80% of the memory if it's dedicated for mysql
### innodb_stats_on_metadata = 0
sql_mode=NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
#STRICT_TRANS_TABLES

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
EOF
    echo mysql_root_pw=$mysql_passwd > /tmp/.mysql_root_pw.$$
    systemctl restart mariadb
}

function iptables_config(){
    echo "start setting firewall"
    systemctl restart firewalld
    firewall-cmd --zone=public --add-port=80/tcp --permanent
    firewall-cmd --zone=public --add-port=5060/udp --permanent
    firewall-cmd --zone=public --add-port=5036/udp --permanent
    firewall-cmd --zone=public --add-port=4569/udp --permanent
    firewall-cmd --zone=public --add-port=10000-20000/udp --permanent
    if [ $? == 0 ];then
        systemctl restart firewalld
    else
        echo -e "\033[33mFirewallD may not running, ignore setting  \033[0m"
    fi
}

function run() {
    dnf -y install wget
    downloadmirror=http://download1.astercc.org

    echo "please select the mirror you want to download from:"
    echo "1: German Server"
    echo "2: U.S. Server"
    echo "3: China Server (China Mobile)"
    read downloadserver;
    RELEASEVER=$(rpm --eval %rhel)

    if [ "$downloadserver" == "1"  ]; then
        downloadmirror=http://download1.astercc.org;
    fi
    if [ "$downloadserver" == "2"  ]; then
        downloadmirror=http://download2.astercc.org;
    fi
    if [ "$downloadserver" == "3"  ]; then
        downloadmirror=http://download3.astercc.org;
    fi

    if [ $RELEASEVER -eq 10 ]; then
        wget $downloadmirror/asterccver1_rocky10 -t 5
        if [ ! -e ./asterccver1_rocky10 ]; then
            echo "failed to get version infromation,please try again"
            exit 1;
        fi
        . ./asterccver1_rocky10
        /bin/rm -rf ./asterccver1_rocky10
    fi

    kernel_upgrade
    dahdi_install
    newRepo_install
    update_system_config
    yum_install
    php_install
    libpri_install
    asterisk_install
    #sngrep_install
    lame_install
    mpg123_install
    nginx_install
    get_mysql_passwd
    set_ami
    systemctl restart asterisk 
    astercc_install
    nginx_conf_install
    logrotate_install
    iptables_config
    echo "asterisk ALL = NOPASSWD :/etc/init.d/asterisk" >> /etc/sudoers
    echo "asterisk ALL = NOPASSWD: /usr/bin/reboot" >> /etc/sudoers
    echo "asterisk ALL = NOPASSWD: /sbin/shutdown" >> /etc/sudoers
    /bin/rm -rf /tmp/.mysql_root_pw.$$
    ln -s /var/lib/asterisk/moh /var/lib/asterisk/mohmp3

    systemctl start php-fpm
    systemctl restart firewalld
    systemctl restart dahdi
    systemctl restart asterisk
    systemctl enable redis
    systemctl start redis
    /opt/asterisk/scripts/astercc/asterccd stop
    systemctl restart astercc.service

    echo -e "\e[32masterCC Commercial installation finish!\e[m";
}

run

