#!/bin/bash
# Author: WYM
# Time:   2024-10-18

# 获取当前工作目录
workdir=$(cd $(dirname $0); pwd)
# 安装日志,拿来控制步骤的
install_log='/tmp/init_Rocky_8.log'

# mysql账号密码
# root
mysql_root_pwd='$$5emnM4qFU$vtFXpBxnjrzyqSkBT!=5'
# program_common
program_pwd='PxJgK@EBw=nncn%7%mk@pJqrW%vbn#xz'

green(){
    echo -e "\033[40;32m$*\033[40;0m"
}

red(){
    echo -e "\033[40;31m$*\033[40;0m"
}

set_blank(){
    echo ''
    echo ''
    echo ''
    echo ''
    cd ${workdir}
    sleep 3
}

echo '***********************************************'
red 'Warning!!!'
red 'Before executing the script'
red 'If you want to install two Percona instances'
red 'The second disk must be mounted under /data/database/mysql_3307 and manually mounted before executing the script'
echo '***********************************************'
echo ""
echo ""
echo ""

read -p 'Have you confirmed the above information? [Yes]' sure
if [ $sure != 'Yes' ];then
    red 'Script exit!!!'
    exit
fi

# 先安装epel和remi源
rpm -qa|grep epel-release > /dev/null 2>&1
if [ $? != '0' ];then
    dnf -y install epel-release
fi
rpm -qa|grep remi-release-8 > /dev/null 2>&1
if [ $? != '0' ];then
    dnf -y install https://rpms.remirepo.net/enterprise/remi-release-8.rpm
fi

# 删除一下不用的repo
rm -f /etc/yum.repos.d/epel-testing-modular.repo /etc/yum.repos.d/epel-testing.repo /etc/yum.repos.d/remi-safe.repo

set_blank

# yum刷新缓存
dnf clean all && dnf makecache

dnf -y install yum-utils

set_blank

# 升级系统
if ! grep 'update_OS-OK' ${install_log} > /dev/null 2>&1;then
    green 'Update OS....'
    dnf -y update
    if [ $? == '0' ];then
        green 'update_OS-OK' >> ${install_log}
        green 'Update OS ------- OK.'
    else
        red 'Update OS ------- Fail.'
    fi
fi

set_blank

green "Open Remi warehouse......"
yum-config-manager --enable remi

set_blank

# 安装系统一些rpm包
if ! grep 'install_other_rpm-OK' ${install_log} > /dev/null 2>&1;then
    green 'Install other RPM toolkits....'
    dnf -y install --enablerepo=devel zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel xz-devel dstat wget mutt dos2unix sudo gcc gcc-c++ expect make openssh-clients net-snmp net-snmp-devel at iptraf lua perl-TermReadKey perl-IO-Socket-SSL perl-Time-HiRes crontabs mlocate vim telnet libffi-devel cmake openssh net-tools lrzsz zip unzip ca-certificates libaio-devel flex jemalloc-devel python36 python36-devel supervisor redis screen lsof iftop autoconf iptables iptables-services iptables-devel iptables-utils libdb-devel.x86_64 libdb-utils.x86_64 clang libstdc++-static gtk2-devel mesa-libGL-devel mesa-libGLU-devel java-1.8.0-openjdk.x86_64 java-1.8.0-openjdk-devel.x86_64
    if [ $? == '0' ];then
        echo "install_other_rpm-OK" >> ${install_log}
        green 'install other rpm tools ------ OK.'
    else
        red 'install other rpm tools ------ Fail.'
		exit 1
    fi
fi

set_blank

# 把一些localinstall的包安装上
green "Install some local install packages."
cd localinstall_rpm
dnf -y localinstall *

set_blank

# 询问你想安装php的什么版本
read -p "Which version of PHP do you want to install? (7.2/8.2)" php_version
if [[ "${php_version}" == '7.2' || "${php_version}" == '8.2' ]];then
    green "PHP ${php_version} is about to be installed"
else
    red "Incorrect PHP version input (7.2 or 8.2)!!!!!"
    exit
fi

set_blank

# 安装PHP
if ! grep "install_php${php_version}-OK" ${install_log} > /dev/null 2>&1;then
    green "Installing PHP ${php_version}...."
    yum-config-manager --enable remi-php$(echo ${php_version}|sed 's@\.@@g')
    unzip php-${php_version}.zip
    cd php-${php_version}
    dnf -y localinstall $(ls -l|grep -v total|awk '{print $NF}'|xargs)
    if [ $? == '0' ];then
        echo "install_php${php_version}-OK" >> ${install_log}
        green "install ${php_version} success."
    else
        red "install ${php_version} fail."
        exit
    fi
fi

set_blank
rm -rf php-${php_version}

# 安装Percona-Server-8.0.35-27
if ! grep 'install_percona-80-OK' ${install_log} > /dev/null 2>&1;then
    green "Installing Percona-Server-8.0.35-27...."
    unzip Percona-Server-8.0.35-27.zip
    cd Percona-Server-8.0.35-27
    dnf -y localinstall $(ls -l|grep -v total|awk '{print $NF}'|xargs)
    
    if [ $? == '0' ];then
        echo 'install_percona-80-OK' >> ${install_log}
        green "install Percona-Server-8.0.35-27 success."
    else
        red "install Percona-Server-8.0.35-27 fail."
        exit
    fi
fi

set_blank
rm -rf Percona-Server-8.0.35-27

# 安装nginx 1.24
if ! grep 'install_nginx-1.24-OK' ${install_log} > /dev/null 2>&1;then
    green "Installing nginx-1.24...."
    unzip nginx-1.24.zip
    cd nginx-1.24
    dnf -y localinstall $(ls -l|grep -v total|awk '{print $NF}'|xargs)
    if [ $? == '0' ];then
        echo 'install_nginx-1.24-OK' >> ${install_log}
        green "install nginx 1.24 success."
    else
        red "install nginx 1.24 fail."
        exit
    fi
fi

set_blank
rm -rf nginx-1.24

# 创建一些文件夹
if ! grep 'mkdir-OK' ${install_log} > /dev/null 2>&1;then
    green 'Create some folders....'
    mkdir -pv /data/log/{mysql,nginx,php,www,rsync,supervisor} /data/games /data/log/php/{opcache,sessions,wsdlcache,cookies} /data/backup/database /data/database/{mysql_3306,mysql_3307} /data/database/mysql_3306/{mysql,mysql-bin} /data/database/mysql_3307/{mysql,mysql-bin} /data/www /data/cores /data/log/nginx/fastcgi_tempfile
    if [ $? == '0' ];then
        echo 'mkdir-OK' >> ${install_log}
        green 'mkdir ------ OK.'
    else
        red 'mkdir ------ Fail.'
    fi
    chown -R dev01.dev01 /data/log/nginx /data/log/php /data/log/www /data/log/rsync /data/log/supervisor /data/www
    chown -R mysql.mysql /data/database/* /data/log/mysql /data/backup/database
    mkdir -pv /var/lib/nginx/tmp/client_body /var/cache/nginx/fastcgi_tempfile && chown -R dev01.dev01 /var/lib/nginx /var/cache/nginx/fastcgi_tempfile && chmod -R 776 /var/lib/nginx /var/cache/nginx/fastcgi_tempfile
fi

set_blank

# 安装vsftpd
if ! grep 'install_vsftpd-OK' ${install_log} > /dev/null 2>&1;then
    green 'Installing vsftpd....'
    if ! rpm -qa|grep vsftpd > /dev/null 2>&1;then
        dnf -y install vsftpd
    fi
    rm -f /etc/vsftpd/vusers.txt /etc/vsftpd/ftpusers /etc/vsftpd/user_list /etc/vsftpd/vsftpd.conf
    \cp -v vsftpd/vusers.txt /etc/vsftpd/vusers.txt
    \cp -v vsftpd/ftpusers /etc/vsftpd/ftpusers
    \cp -v vsftpd/user_list /etc/vsftpd/user_list
    \cp -v vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.conf
    #文件夹user_conf
    if [ ! -d /etc/vsftpd/user_conf ];then
        mkdir /etc/vsftpd/user_conf
    fi
    # 复制用户
    \cp -v vsftpd/vusers.txt /etc/vsftpd/vusers.txt

    #4、vi /etc/pam.d/vsftpd.virtual
    cat>/etc/pam.d/vsftpd.virtual<<EOF
#PAM-1.0
auth    required    pam_userdb.so   db=/etc/vsftpd/vsftpd-virtual-user
account required    pam_userdb.so   db=/etc/vsftpd/vsftpd-virtual-user
session required    pam_loginuid.so
EOF

    if [ ! -d /data/vsftpd_root ];then
    mkdir -pv /data/vsftpd_root
    chown -R dev01.dev01 /data/vsftpd_root
    chmod -R 775 /data/vsftpd_root
    fi
    cd /etc/vsftpd
    if [ -f vsftpd-virtual-user.db ];then
        rm -f vsftpd-virtual-user.db
    fi
    db_load -T -t hash -f vusers.txt vsftpd-virtual-user.db
    chmod 600 vusers.txt vsftpd-virtual-user.db

    systemctl disable vsftpd
    systemctl start vsftpd
    if [ $? == '0' ];then
        echo 'install_vsftpd-OK' >> ${install_log}
        green 'install vsftpd ------- OK.'
    else
        red 'install vsftpd ------- Fail.'
    fi
fi

set_blank

# 安装rsyncd
if ! grep 'install_rsync-OK' ${install_log} > /dev/null 2>&1;then
    green "Installing rsyncd...."
    if ! rpm -qa|grep rsync > /dev/null 2>&1;then
        dnf -y install rsync
    fi
    \cp -v rsyncd.conf /etc/rsyncd.conf
    \cp -v rsyncd.secrets /etc/rsyncd.secrets
    \cp -v rsyncd.client /etc/rsyncd.client
    chmod 600 /etc/rsyncd.secrets /etc/rsyncd.client
	if [ ! -f /etc/systemd/system/rsyncd.service ];then
	cat >/etc/systemd/system/rsyncd.service<<EOF
[Unit]
Description=Remote Sync
After=network.target
 
[Service]
Type=forking
ExecStart=/usr/bin/rsync --daemon
KillSignal=SIGTERM
 
[Install]
WantedBy=multi-user.target
EOF
	fi
    systemctl enable rsyncd.service
    systemctl start rsyncd.service
    if [ $? == '0' ];then
        echo 'install_rsync-OK' >> ${install_log}
        green 'install rsyncd ------ OK.'
    else
        red 'install rsyncd ------ Fail.'
    fi
fi

set_blank

# 优化sysctl
if ! grep 'init_sysctl-OK' ${install_log} > /dev/null 2>&1;then
    green 'Optimize system sysctl....'
    \cp -v /etc/sysctl.conf /etc/sysctl.conf_bak_init
    \cp -v sysctl.conf /etc/sysctl.conf
    sysctl -p
    echo 'init_sysctl-OK' >> ${install_log}
    green "init sysctl ------- OK."
fi

set_blank

# 优化系统资源
if ! grep 'init_system_source-OK' ${install_log} > /dev/null 2>&1;then
    green 'Optimize system resources....'
    cat >/etc/security/limits.d/20-nproc.conf<<EOF
*       soft    nproc   65535
*       hard    nproc   65535
EOF

    while true
    do
        line=`tail -n1 /etc/security/limits.conf`
        if [[ ${line} != '# End of file' ]];then
            sed -i '$d' /etc/security/limits.conf
            if [ $? == '0' ];then
                green "delete '${line}' success...."
            fi
        else
            break
        fi
    done

    cat >>/etc/security/limits.conf<<EOF
*           soft  core   unlimited 
*           hard  core   unlimited 
*           soft  fsize  unlimited 
*           hard  fsize  unlimited 
*           soft  data   unlimited 
*           hard  data   unlimited 
*           soft  nproc  65535 
*           hard  nproc  63535 
*           soft  stack  unlimited 
*           hard  stack  unlimited 
*           soft  nofile  409600 
*           hard  nofile  409600
EOF
    echo 'init_system_source-OK' >> ${install_log}
    green 'init system source ------ OK.'
fi

set_blank

# 初始化Percona
if ! grep 'init_Percona-OK' ${install_log} > /dev/null 2>&1;then
    rm -f /data/log/mysql/*
    green 'Initialize single instance Percona server....'
    \cp /etc/my.cnf /etc/my.cnf_bak_init
    rm -f /etc/my.cnf
    read -p "Do you want to install a single instance or a dual instance? [Single instance ->1 dual instance ->2]" answer
    if [[ ${answer} == '1' || ${answer} == '2' ]];then
        green "You have selected ${answer} MySQL instances"
    else
        red 'Please select the correct number of instances.'
        exit
    fi
    if [ ${answer} == '1' ];then
        systemctl enable mysqld
        \cp -v my.cnf_single-mysql /etc/my.cnf
        \cp -v .bashrc_single-mysql /root/.bashrc
        systemctl start mysqld
        if lsof -i:3306 >/dev/null 2>&1;then
            green "mysql start success."
            mysql_password=`grep 'A temporary password is generated for' /data/log/mysql/error.log |awk '{print $NF}'|sed 's/ //g'`
            green "************************************************"
            green "Please copy the password change statement below:"
            echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '${mysql_root_pwd}';"
            green "************************************************"
            mysql -uroot -p${mysql_password} -S /var/lib/mysql/mysql.sock
            mysql -uroot -p${mysql_root_pwd} -S /var/lib/mysql/mysql.sock -e "create user 'program_common'@'127.0.0.1' identified by '${program_pwd}';"
            mysql -uroot -p${mysql_root_pwd} -S /var/lib/mysql/mysql.sock -e "grant all privileges on *.* to 'program_common'@'127.0.0.1';"
            mysql -uroot -p${mysql_root_pwd} -S /var/lib/mysql/mysql.sock -e "flush privileges;"
        else
            red "mysql start fail!!!!"
        fi
    fi
    if [ ${answer} == '2' ];then
        systemctl disable mysqld
        green 'Initialize the [Dual Instance] instance Percona server....'
        \cp -v my.cnf_double-mysql /etc/my.cnf
        \cp -v .bashrc_double-mysql /root/.bashrc
        green 'Initialize the 3306 instance....'
        systemctl start mysqld@3306
        if lsof -i:3306 >/dev/null 2>&1;then
            green "mysql 3306 start success."
            mysql_password=`grep 'A temporary password is generated for' /data/log/mysql/error.log |awk '{print $NF}'|sed 's/ //g'`
            green "************************************************"
            green "Please copy the password change statement below:"
            echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '${mysql_root_pwd}';"
            green "************************************************"
            mysql -uroot -p${mysql_password} -S /var/lib/mysql/mysql.sock
            mysql -uroot -p${mysql_root_pwd} -S /var/lib/mysql/mysql.sock -e "create user 'program_common'@'127.0.0.1' identified by '${program_pwd}';"
            mysql -uroot -p${mysql_root_pwd} -S /var/lib/mysql/mysql.sock -e "grant all privileges on *.* to 'program_common'@'127.0.0.1';"
            mysql -uroot -p${mysql_root_pwd} -S /var/lib/mysql/mysql.sock -e "flush privileges;"
        else
            red "mysql 3306 start fail!!!!"
        fi
        set_blank
        green 'Initialize the 3307 instance....'
        systemctl start mysqld@3307
        if lsof -i:3307 >/dev/null 2>&1;then
            green "mysql 3307 start success."
            mysql_password=`grep 'A temporary password is generated for' /data/log/mysql/error_3307.log |awk '{print $NF}'|sed 's/ //g'`
            green "************************************************"
            green "Please copy the password change statement below:"
            echo "ALTER USER 'root'@'localhost' IDENTIFIED BY '${mysql_root_pwd}';"
            green "************************************************"
            mysql -uroot -p${mysql_password} -S /var/lib/mysql/mysql_3307.sock
            mysql -uroot -p${mysql_root_pwd} -S /var/lib/mysql/mysql_3307.sock -e "create user 'program_common'@'127.0.0.1' identified by '${program_pwd}';"
            mysql -uroot -p${mysql_root_pwd} -S /var/lib/mysql/mysql_3307.sock -e "grant all privileges on *.* to 'program_common'@'127.0.0.1';"
            mysql -uroot -p${mysql_root_pwd} -S /var/lib/mysql/mysql_3307.sock -e "flush privileges;"
        else
            red "mysql 3307 start fail!!!!!"
        fi
    fi
    mkdir -p /etc/save/
    echo ${mysql_root_pwd} > /etc/save/mysql_root
    echo 'init_Percona-OK' >> ${install_log}
    green 'init Percona ------ OK.'
fi

set_blank

# 初始化php-fpm
if [ ${php_version} == '8.2' ];then
    sub_dir='php-fpm82_conf'
	conf_dir='/etc/opt/remi/php82'
	bin_dir='/opt/remi/php82/root/bin'
else
    sub_dir='php-fpm72_conf'
	conf_dir='/etc/opt/remi/php72'
	bin_dir='/opt/remi/php72/root/bin'
fi
if ! grep 'init_php-fpm-OK' ${install_log} > /dev/null 2>&1;then
    green "Initializing PHP version ${php_version}...."
    rm -f ${conf_dir}/php.ini
    rm -f ${conf_dir}/php-fpm.conf
    rm -f ${conf_dir}/php-fpm.d/www.conf
    \cp -v ${sub_dir}/php.ini ${conf_dir}
    \cp -v ${sub_dir}/php-fpm.conf ${conf_dir}
    \cp -v ${sub_dir}/www.conf ${conf_dir}/php-fpm.d
    if [ -f ${conf_dir}/php.d/20-oci8.ini ];then
        mv ${conf_dir}/php.d/20-oci8.ini ${conf_dir}/php.d/20-oci8.ini_bak
    fi
    if [ -f ${conf_dir}/php.d/30-pdo_oci.ini ];then
        mv ${conf_dir}/php.d/30-pdo_oci.ini ${conf_dir}/php.d/30-pdo_oci.ini_bak
    fi
	if [ ${php_version} == '8.2' ];then
		systemctl enable php82-php-fpm.service
		systemctl start php82-php-fpm.service
	else
		systemctl enable php72-php-fpm.service
		systemctl start php72-php-fpm.service
	fi
    echo 'init_php-fpm-OK' >> ${install_log}
    green 'init php-fpm ------ OK.'
fi

set_blank

# 初始化nginx
if ! grep 'init_nginx-OK' ${install_log} > /dev/null 2>&1;then
    green 'Initialization nginx....'
    rm -rf /etc/nginx
    \cp -vR nginx /etc/
    systemctl enable nginx
    systemctl start nginx
    echo 'init_nginx-OK' >> ${install_log}
    green 'init nginx ------ OK.'
fi

set_blank

# 安装swoole(安装8.2的时候才安装)
if [ ${php_version} == '8.2' ];then
	if ! grep 'install_swoole-OK' ${install_log} > /dev/null 2>&1;then
		green 'Installing PHP的swoole module....'
		tar xf swoole-src-5.0.3.tar.gz
		cd swoole-src-5.0.3
		
		${bin_dir}/phpize
		./configure --with-php-config=${bin_dir}/php-config

		make
		make install
		echo 'extension=swoole' > ${conf_dir}/php.d/60-swoole.ini
		echo 'install_swoole-OK' >> ${install_log}
		green 'install swoole ------ OK.'
		cd .. && rm -rf swoole-src-5.0.3
	fi
else
	red "The selected version is ${php_version}, and there is no need to install swoole-5.0.3!"
fi

set_blank

# 安装wxWidgets-3.0.1
if ! grep 'install_wxWidgets-3.0.1-OK' ${install_log} > /dev/null 2>&1;then
    green 'Installing wxWidgets-3.0.1....'
    tar xf wxWidgets-3.0.1.tar.bz2
    cd wxWidgets-3.0.1
    ./configure
    make
    make install
    echo 'install_wxWidgets-3.0.1-OK' >> ${install_log}
    green 'Install wxWidgets-3.0.1 ------ OK.'
fi

set_blank
rm -rf wxWidgets-3.0.1

# 安装openssl-1.0.2k
if ! grep 'openssl-1.0.2k-OK' ${install_log} > /dev/null 2>&1;then
    green 'Installing openssl-1.0.2k....'
    tar xf openssl-1.0.2k.tar.gz
    cd openssl-1.0.2k
    ./config -fPIC --prefix=/usr/local/openssl
    make
    make install
    echo 'openssl-1.0.2k-OK' >> ${install_log}
    green 'Install openssl-1.0.2k ------ OK.'
fi

set_blank
rm -rf openssl-1.0.2k

# 安装erlang 19
if ! grep 'install_erlnag19-OK' ${install_log} > /dev/null 2>&1;then
    green 'Installing Erlang 19....'
    tar xf otp-OTP-19.3.6.13.tar.gz
    cd otp-OTP-19.3.6.13
	export ERL_TOP=`pwd`
    ./otp_build autoconf
    ./configure --prefix=/usr/local/erlang --with-ssl=/usr/local/openssl
	export LANG=C
    make
    make install
    echo 'install_erlnag19-OK' >> ${install_log}
    green 'install Erlang 19 ------ OK.'
fi

set_blank
rm -rf otp-OTP-19.3.6.13

cat >>/etc/profile<<EOF

export ERLANG_HOME=/usr/local/erlang/bin
export PATH=\$PATH:\$ERLANG_HOME
EOF

green "Copy the template file for iptables to /etc/sysconfig...."
\cp -v iptables /etc/sysconfig/iptables

set_blank

green "Copy the Vim optimization file. vimrc to /root...."
\cp -v .vimrc /root/.vimrc

set_blank

# 安装zabbix-agent
if ! grep 'install_zabbix-agent-OK' ${install_log} > /dev/null 2>&1;then
    green 'Installing zabbix_agent....'
    cd install_zabbix_agent_4.0.50_Centos7-Rocky8
    sh install_agent_4.0.50.sh
    echo 'install_zabbix-agent-OK' >> ${install_log}
    green 'init zabbix-agent ------ OK.'
fi
cd ${workdir}
rm -rf install_zabbix_agent
set_blank

read -p'What is the external IP address of the machine:' outer_ip

cat >/etc/nginx/conf.d/phpinfo.conf<<EOF
server {
    listen                          80;
    server_name                     mathine_outer_ip;
    root                            /data/www/phpinfo;

    location ~ \.php 
    {
        fastcgi_pass  unix:/dev/shm/php-cgi.sock;
        fastcgi_index index.php;
        include       fastcgi.conf;
        set \$path_info "";
        set \$real_script_name \$fastcgi_script_name;
        if (\$fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
                set \$real_script_name \$1;
                set \$path_info \$2;
        }
        fastcgi_param SCRIPT_FILENAME \$document_root\$real_script_name;
        fastcgi_param SCRIPT_NAME \$real_script_name;
        fastcgi_param PATH_INFO \$path_info;                
    }
}
EOF

sed -i "s@mathine_outer_ip@${outer_ip}@g" /etc/nginx/conf.d/phpinfo.conf

mkdir -pv /data/www/phpinfo

set_blank

\cp -v info.php /data/www/phpinfo

chown -R dev01.dev01 /data/www/phpinfo

if [ ${php_version} == '8.2' ];then
	systemctl enable php82-php-fpm.service
	systemctl start php82-php-fpm.service
else
	systemctl enable php72-php-fpm.service
	systemctl start php72-php-fpm.service
fi
systemctl restart nginx
systemctl disable postfix
systemctl stop firewalld
systemctl disable firewalld
systemctl disable rsyncd
systemctl disable vsftpd

set_blank

green "http://${outer_ip}/info.php"
