#!/bin/bash

#最新版下载地址  http://download.hyahm.com/hyahm.sh
#########################  nginx var  #############################

#如果找最新稳定的拓展包，请查看此网址  http://www.hardyliu.me/packages/tar/nginx
#爆出nginx漏洞，最新版不支持3方模块，已经屏蔽
osuser=$(id -u)
if [[ $osuser -ne 0 ]];then
	echo "must be run script as root"
	exit 1
fi


function nginxvar {
	#server名称
	com="hyahm.com"
	#服务的名称 *****
	nginxversion=nginx-1.14.0

	#ngixnx安装目录 *****
	nginxpath="/usr/local/nginx"
	#nginx的pid文件路径,如果路劲修改，清确认是否有此目录
	nginx_dir="/run/"	
	nginx_pid=${nginx_dir}"/nginx.pid"
	#nginx虚拟主机的目录
	vhostdir="vhost"
	#如果上面有添加新的包，请在此处添加变量，编辑的时候增加模块
	#tz_arr=(${lua} ${kit} ${redis} ${drizzle} ${json} ${echo} ${set_misc} ${vts} ${purge} ${drizzle7} ${luajit})
}


##########################  mysql var  ######################
function mysqlvar {
	#版本号,mysql太坑，不建议修改，如果修改导致无法下载对应版本，请下载后解压到/usr/local/src下面
	mysqlversion="5.7.26"
	#mysqlversion="5.6.39"
	#mysqlversion="5.5.59"
	#mysql的服务名字 *****
	#mysql socket
	mysqlsock="/tmp/mysql.sock"
	#mysql运行用户
	mysqluser="mysql"
	#mysql配置文件   如果路劲修改，清确认是否有此目录  *****
	mysql_config_file="/etc/my.cnf"
	#数据库目录
	mysqldata="/usr/local/mysql/data"
	#固定值
	mysqlv=${mysqlversion%.*}
	if [ "${mysqlv}" = "5.7" ]
	then
		mysqldown="mysql-boost-${mysqlversion}"
	
	else
		mysqldown="mysql-${mysqlversion}"
	fi
	mysql="mysql-${mysqlversion}"
	#mysql安装目录  *****
	mysqlpath="/usr/local/mysql"
	#mysql初始密码
	rootpwd='123456'
	#是否启用编译加速，0为不加速，1为加速，如果内存小于cpu核心*1G，不建议开启
	tofast=1
	
}
######################### php var #########################
function phpvar {
	#php版本 
	phpversion="php-7.2.10"	
	#php运行的用户
	phpuser="nginx"
	#php-fpm慢日志
	phplog="/data/php/log/"
	#php运行端口****
	phpport=9000
	#最新更新，php5使用1.9  php7使用2.0
	#swooleversion=2
	#php-fpm启动服务的名字  *****
	#获取php版本
	phpnum=`echo "${phpversion}" | awk -F - '{print $2}' | awk -F . '{print $1}'`
	#php安装目录  ****
	phppath="/usr/local/"
	#php配置文件   ****
	phpconfig="/etc/"
	#php错误日志文件存放位置
	php_err_log="/data/logs"
	#php扩展放置目录，修改无效
	php_ext_dir=`cat /usr/local/src/${phpversion}/Makefile | grep "EXTENSION_DIR =" | awk '{print $3}'`
	
}

########################   postgresql var   ##############################

function postgresqlvar {
	#版本
	postgresqlversion="postgresql-9.6.3"
	#下载地址专用，勿修改
	downloadpathdir=`echo "${postgresqlversion}" | awk -F - '{print $2}'`
	#安装目录
	postgresqlpath='/usr/local/postgresql'
	#执行用户
	postgresqluser='postgres'
	#数据库目录
	postgresqldata='/usr/local/postgresql/data'
	#启动脚本的名字，非必要时不用动，就开机自启会用到
	postgresqlservername='postgresql'
	#socket 文件目录
    postgresqlsocket='/var/run/postgresql'	
	#日志目录
	postgresqllog='/usr/local/postgresql/data/serverlog'
}


#########################   zabbix var   #####################
function zabbixvar {
	#zabbix版本（源码编译版本）
	zabbixversion="zabbix-3.2.3"
	#下载固定变量
	zabbixdownload=`echo ${zabbixversion} | awk -F - '{print $2}'`
	#zabbix路径
	zabbixpath="/usr/local/zabbix"
	#本机mysql的root密码
	mysqlpassword="123456"
	#zabbix的数据库账号
	zabbixmysqluser="zabbix"
	#abbix的数据库密码
	zabbixmysqlpassword='123456'
	#nginx虚拟主机配置文件目录
	nginxconfigpath="/usr/local/nginx/conf/vhost"
	#zabbixweb目录
	zabbixwebpath="/var/www/zabbix"
	
	#zabbix网站的端口
	zabbixport=10001
	#zabbix db name
	zabbixdb="zabbix"
	#php.ini文件
	zabbixphp="/etc/php.ini"
	############## zabbixagent  #####	
	abbixserverip=""		
	#不需要修改
	zabbixagenthostname=$(hostname)
}

######################## ftp var   #################################

function ftpvar {
	#用户名
	ftpuser='test'
	#密码
	ftppassword='123456'
	#共享的虚拟账号后缀
	webname="test"
	#共享的目录
	homedir="/var/www"

}


######################## public var  #####################

function public {
#内存大小,单位M
memsize=`free -m | grep Mem | awk '{print $2}'`

#cpu的线程数
cpunu=`cat /proc/cpuinfo | grep processor | wc -l`
#查看系统版本
version=`cat /etc/redhat-release  | awk '{print $(NF-1)}' | awk -F . '{print $1}'`
if [ "${version:0:1}" = "(" ];then
	version=7
fi

yum update -y nss curl libcurl 
#openfile的值
sysctln=1000000
grep "* soft nofile ${sysctln}" /etc/security/limits.conf
if [ $? -ne 0 ];then
cat >>/etc/security/limits.conf <<EOF
* soft nofile ${sysctln}
* hard nofile ${sysctln}
EOF
echo "ulimit -n ${sysctln}" >> ~/.bashrc
source ~/.bashrc
fi

#外网ip
mynetip=`curl -s http://members.3322.org/dyndns/getip`
#主机名
hostname=`hostname`

#安装常用的vim并设置tab4个空格
yum -y install vim iproute
grep "set ts=4"  /etc/vimrc
if [ $? -ne 0 ]
then
	echo "set ts=4" >> /etc/vimrc
fi
#,添加中文乱码解决
grep "set enc=utf8"  /etc/vimrc
if [ $? -ne 0 ]
then
	echo "set enc=utf8" >> /etc/vimrc
fi

#添加环境变量
grep "export PATH=\$PATH:/usr/local/bin" /etc/bashrc
if [ $? -ne 0 ]
then
	echo "export PATH=\$PATH:/usr/local/bin" >> /etc/bashrc
	source /etc/bashrc
fi
#我的内网ip
if [ "${version}" = "7" ]
then
	#ip个数
	ipnu=`ip addr | grep inet | grep -v inet6 | grep -v "lo$" | wc -l`
	if [ ${ipnu} -eq 1 ]
	then 		
		mynetip=`ip addr | grep inet | grep -v inet6 | awk '{print $2}' | awk -F / '{print $1}'  | grep -v 127.0.0.1`	
	fi
else
	#ip个数
   	ipnu=`ifconfig | grep inet | grep -v inet6 | awk '{print $2}' | grep -v 127.0.0.1 | wc -l`
 	if [ ${ipnu} -eq 1 ]
	then
		mynetip=`ifconfig | grep inet | grep -v inet6 | awk '{print $2}' | grep -v 127.0.0.1`
	fi
fi

#同步时间
which ntpdate &> /dev/null
if [ $? -ne 0 ]
then
	yum -y install ntpdate	
fi
ntpdate ntp1.aliyun.com
if [ $? -eq  0 ]
then
	echo "同步时间成功"
else
	echo "同步时间失败"
fi 
#安装epel源
if [  "${version}" = "7"  ]
then
	yum -y install epel-release
	if [ $? -ne 0 ]
	then
		sed -i 's/gpgcheck=1/gpgcheck=0/g' /etc/yum.repos.d/epel.repo
	fi
else
	rpm -ivh http://mirrors.hust.edu.cn/epel/6/x86_64/epel-release-6-8.noarch.rpm 
	sed -i 's/gpgcheck=1/gpgcheck=0/g' /etc/yum.repos.d/epel.repo
fi

# 关闭防火墙
service iptables stop
setenforce 0 
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config


#如果是7版本还需要停用firewalld
if [ ${version} -eq 7 ]
	then
        	systemctl stop firewalld &> /dev/null
        	systemctl disable firewalld &> /dev/null
fi
#安装依赖
	yum -y install wget git initscripts gcc make  systemd xz
}

######################################   start nginx    ###################################
#nginx包
function download_nginx {
cd 
if [ ! -d /usr/local/src/${nginxversion} ]
 then
 	rm -f ${nginxversion}.tar.gz
     wget -O ${nginxversion}.tar.gz    http://nginx.org/download/${nginxversion}.tar.gz
     tar -xf ${nginxversion}.tar.gz -C  /usr/local/src
	 
fi
}

#隐藏版本
function yincang {
	sed -i 's#"nginx/" NGINX_VERSION#"test"#g' /usr/local/src/${nginxversion}/src/core/nginx.h
	sed -i "s/test/${com}/g" /usr/local/src/${nginxversion}/src/core/nginx.h
	sed -i "29s#nginx#${com}#g" /usr/local/src/${nginxversion}/src/http/ngx_http_special_response.c
	sed -i "s#Server: nginx#Server: ${com}#g" /usr/local/src/${nginxversion}/src/http/ngx_http_header_filter_module.c
	
}

#其他拓展包
#function packages {
#if [ ! -d /package ]
#  then#
#	mkdir /package
#fi

#cd /package
#for((i=0;i<${#tz_arr[@]};i++))
#do
#if [ ! -f ${tz_arr[$i]}.tar.gz ]
#  then  
#  	rm -f ${tz_arr[$i]}.tar.gz#
#	wget  http://download.hyahm.com/${tz_arr[$i]}.tar.gz
#	tar -xf ${tz_arr[$i]}.tar.gz -C /usr/local/src
#	wait
#fi
#done 

#}
#安装依赖包
function nginxdepend {
    yum -y install autoconf  libtool fcgi-devel  gcc perl-devel perl-ExtUtils-Embed perl pcre-devel   zlib-devel  openssl-devel   lua-devel  gcc-c++
}

#安装libdirzzle依赖
#function install_libdirzzle {
#	cd  /usr/local/src/${drizzle7}
#        ./configure --without-server
#        make libdrizzle-1.0
#        make install-libdrizzle-1.0
#}

#下载nginx-sticky-module模块
function add_sticky {
	if [ ! -d  /usr/local/src/nginx-sticky-module-ng ]
	then
		cd
		rm -f nginx-sticky-module-ng.git
		cd /usr/local/src
		git clone https://github.com/bymaximus/nginx-sticky-module-ng.git
		if [ $? -ne 0 ]
		then
			yum update -y nss curl libcurl  
			git clone https://github.com/bymaximus/nginx-sticky-module-ng.git
		fi
	fi
}


#安装nginx
function install_nginx {
	if [ ! -d ${nginxpath} ]
	then
		mkdir -p ${nginxpath}
	fi
	if [ ! -d ${nginx_dir} ]
    then
        mkdir ${nginx_dir}
    fi
	if [ -f ${nginxpath}/sbin/nginx ]
    then
       rm -f ${nginxpath}/sbin/nginx
	   rm -f /usr/local/bin/nginx
    fi   
		cd /usr/local/src/${nginxversion}		
		./configure \
		--prefix=${nginxpath} \
		 --with-http_dav_module \
		--with-http_stub_status_module \
		--with-http_addition_module \
		--with-http_sub_module \
		--with-http_flv_module \
		--with-http_mp4_module \
		--with-pcre \
		--with-stream \
		--with-http_ssl_module  \
		  --with-http_gzip_static_module \
		 --with-file-aio \
		 --with-pcre-jit \
		--with-http_perl_module \
		 --with-http_v2_module \
		 --with-http_realip_module \
		 --with-http_gunzip_module \
		--with-ld-opt="-Wl,-rpath,/usr/local/lib" 
		#--add-module=/usr/local/src/nginx-sticky-module-ng 
		if [ $? -ne 0 ]
		then
			echo "编译错误"
			exit 1
		fi
		make -j ${cpunu} && make install
		ln -s ${nginxpath}/sbin/nginx  /usr/local/bin/nginx
}

#添加luajit
function addluajit {
	cd /usr/local/src/${luajit}
	make -j ${cpunu} && make install 
	echo "LUAJIT_LIB=/usr/local/lib" >> /etc/profile
	echo "LUAJIT_INC=/usr/local/include/luajit-2.0" >> /etc/profile
	source /etc/profile
}

#创建用户组
function user_group {
	cat /etc/passwd | grep "^nginx:"
	if [ $? -ne 0 ]
	then
		groupadd nginx
		useradd -g nginx -s /sbin/nologin nginx
	fi
}

#配置文件
function nginxconf {
if [ ${version} -eq 7 ];then
	# 判断是否存在目录, 存在就继续
	cat > /usr/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=${nginx_pid}
ExecStartPre=${nginxpath}/sbin/nginx -t -c ${nginxpath}/conf/nginx.conf
ExecStart=${nginxpath}/sbin/nginx -c ${nginxpath}/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target	
EOF
	systemctl daemon-reload	
	systemctl enable nginx
	pkill nginx
else
		cat>/etc/init.d/nginx<<"EOF"
#!/bin/bash
# nginx Startup script for the Nginx HTTP Server
# it is v.0.0.2 version.
# chkconfig: - 85 15
# description: Nginx is a high-performance web and proxy server.
# processname: nginx
# pidfile: /var/run/nginx.pid
# config: /usr/local/nginx/conf/nginx.conf
nginxd=ppppp/sbin/nginx
nginx_config=ppppp/conf/nginx.conf
nginx_pid=/run/nginx.pid
RETVAL=0
prog="nginx"
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0
[ -x $nginxd ] || exit 0
# Start nginx daemons functions.
start() {
if [ -e $nginx_pid ];then
   echo "nginx already running...."
   exit 1
fi
   echo -n $"Starting $prog: "
   daemon $nginxd -c ${nginx_config}
   RETVAL=$?
   echo
   [ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
   return $RETVAL
}
# Stop nginx daemons functions.
stop() {
        echo -n $"Stopping $prog: "
        killproc $nginxd
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /var/run/nginx.pid
}
# reload nginx service functions.
reload() {
    echo -n $"Reloading $prog: "
    killproc $nginxd -HUP
    RETVAL=$?
    echo
}
# See how we were called.
case "$1" in
start)
        start
        ;;
stop)
        stop
        ;;
reload)
        reload
        ;;
restart)
        stop
        start
        ;;
status)
        status \$prog
        RETVAL=$?
        ;;
*)
        echo $"Usage: $prog {start|stop|restart|reload|status|help}"
        exit 1
esac
exit $RETVAL
EOF
	sed -i "s#ppppp#${nginxpath}#g" /etc/init.d/nginx
	chmod +x /etc/init.d/nginx
	chkconfig --add nginx
	chkconfig nginx on	
	pkill nginx
fi
nginx
}

#优化部分待补充
function nginxyouhua {
	if [ ! -d ${nginxpath}/conf/${vhostdir} ]
	then 
	 	mkdir -p ${nginxpath}/conf/${vhostdir}
	fi
	if [ -f ${nginxpath}/conf/nginx.conf ]
	then
		rm -f ${nginxpath}/conf/nginx.conf
	fi
	mkdir ${nginxpath}/conf/ssl
	cat> ${nginxpath}/conf/safe.conf <<EOF
#防止wget -m获取网站代码和ab压力测试
if (\$http_user_agent ~* (Wget|ab)) {
        return 403;
}
#禁用非必要的请求方式
if (\$request_method !~ (GET|HEAD|POST)) {
	return 405;
}
EOF
	cat> ${nginxpath}/conf/proxy.conf <<EOF
	   proxy_redirect  off;
    #获取用户真实的IP以及代理的真实IP
    proxy_set_header   Host   \$host;	
    proxy_set_header  X-Real-IP  \$remote_addr;
	proxy_set_header REMOTE-HOST \$remote_addr;
    proxy_set_header  X-Forwarded-For   \$proxy_add_x_forwarded_for;
    #客户端请求主体的缓冲大小，先保存到本地然后发给客户端
    client_body_buffer_size   200M;
    #客户端连接客户端的超时时间
    proxy_connect_timeout   90;
    #后端服务器响应的时间
    proxy_send_timeout    90;
    #后端服务器读取时间
    proxy_read_timeout    90;
    #缓存区大小
    proxy_buffer_size    4k;
    proxy_buffers   4    32k;
    #最大缓存区proxy_buffers * 2
    proxy_busy_buffers_size   64k;
    #临时缓存区
    proxy_temp_file_write_size   64k;	
	 proxy_set_header Access-Control-Allow-Origin \$http_origin;
	#缓存
	
    #proxy_cache_path /data/cache/proxy_cache levels=1:2 keys_zone=cache_one:500m inactive=30d max_size=3072g;
   

EOF
	cat > ${nginxpath}/conf/${vhostdir}/upstream.conf <<EOF
#ip_hash  每个请求按访问ip的hash结果分配，这样每个访客固定访问一个后端服务器，可以解决session的问题
#down 表示单前的server暂时不参与负载 
#weight 默认为1.weight越大，负载的权重就越大。 
#max_fails ：允许请求失败的次数默认为1.当超过最大次数时，返回proxy_next_upstream 模块定义的错误 
#fail_timeout:max_fails次失败后，暂停的时间。 
#backup： 其它所有的非backup机器down或者忙的时候，请求backup机器。所以这台机器压力会最轻
upstream proxy_test1 {
	#这里weight不是说这边请求5次后再去请求另外一台，而是大概的比例值
	least_conn;     #最小连接优先
    server 192.168.2.231:8008 weight=1;
    server 192.168.2.126:8001 weight=1;

}
upstream proxy_test2 {
	#每个请求按访问ip的hash结果分配，这样每个访客固定访问一个后端服务器，可以解决session的问题,比例大概也是1:1
	ip_hash;
    server 192.168.2.231:8008;
    server 192.168.2.126:8001;

}

EOF
	cat > ${nginxpath}/conf/${vhostdir}/default.conf.template <<"EOF"
server {
        listen       80;
        server_name  test.hyahm.com;
        root   /var/www/test;
        charset utf-8;
		index index.php index.html;
        #限制并发连接数；
        limit_conn  perip 10;
        #access_log  logs/host.access.log  main;
        #错误日志等级  debug,info,notice,warn,error,crit;
        #add ssl,in ssl.conf you must add key file
        #include ssl.conf;
        error_log logs/wp_error.log ;
    #location  ~ \.(rar|zip|7z|gz)$ {
       #    ###限制下载：下载路径添加过期时间签名
       #    proxy_cache cache_one;
       #    proxy_cache_valid  200 304 301 302 7d;
       #    #限制单次下载速度
       #    limit_rate 600k;
       #    expires 3d;
    #}
    #禁用非必要的请求方式
            if ($request_method !~ (GET|HEAD|POST)) {
                return 405;
            }

    #清除指定缓存的模块，如果添加了缓存模块必须要增加此模块
    #清楚某个地址的缓存格式
    #curl -H "域名" 地址   （把地址的域名换成127.0.0.1/purge就可以了）
        #location ~ /purge(/.*) {
        #    #设置只允许指定的IP或IP段才可以清除URL缓存。
        #    allow   127.0.0.1;
        #    deny    all;
        #    proxy_cache_purge  cache_one ;
        #    error_page 405 =200 /purge;
        #}

        location / {

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
     location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

        #jsp代码交给tomcat处理
        #location ~ .*\.jsp$ {
        #       index index.jsp;
        #       proxy_pass http://localhost:8080;
        #}
        
}
EOF
cat > ${nginxpath}/conf/${vhostdir}/vue.conf.template <<"EOF"
server {
        listen 7070;
        server_name localhost;
        root /dist;
        index index.html;


        location / {
        	try_files $uri $uri/ @router;
        	index index.html;
        }


        location @router {
        	rewrite ^.*$ /index.html last;
        }
}
EOF
cat > ${nginxpath}/conf/${vhostdir}/thinkphp.conf.template <<"EOF"
server {
    listen       80;
    server_name  thinkphp.com;
    root /var/www/thinkphp;
    index  index.html index.htm index.php;
    error_log logs/error.log;
    location = /404.html {
        return 404 'Sorry, File not Found!';
    }
  
    location / {
        try_files $uri @rewrite;
    }
    location @rewrite {
        set $static 0;
        if  ($uri ~ \.(css|js|jpg|jpeg|png|gif|ico|woff|eot|svg|css\.map|min\.map)$) {
            set $static 1;
        }
        if ($static = 0) {
            rewrite ^/(.*)$ /index.php?s=/$1;
        }
    }
    location ~ /Uploads/.*\.php$ {
        deny all;
    }
    location ~ \.php/ {
       if ($request_uri ~ ^(.+\.php)(/.+?)($|\?)) { }
       fastcgi_pass 127.0.0.1:9000;
       include fastcgi_params;
       fastcgi_param SCRIPT_NAME     $1;
       fastcgi_param PATH_INFO       $2;
       fastcgi_param SCRIPT_FILENAME $document_root$1;
    }
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    location ~ /\.ht {
        deny  all;
    }
}


EOF

cat > ${nginxpath}/conf/${vhostdir}/laraval.conf.template <<"EOF"
server {
 	listen 80;
 	server_name laraval.com;
 	root /var/www/laraval/public;
 

 	index index.html index.htm index.php;
 
 	charset utf-8;
    #设置加载 css flash txt js 图片等资源
    location ~* ^.+\.(jpg|jpeg|gif|png|bmp|css|js|swf|txt)$ {
        access_log off; 
        break;  
    }


    location / { 
        try_files \$uri \$uri/ /index.php?\$query_string;
        index index.php index.html index.htm;
    } 

    #
    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}
 
}
EOF

	cat > ${nginxpath}/conf/ssl.conf <<EOF
#ssl参考配置
ssl_certificate ssl/server.crt;
ssl_certificate_key ssl/server.key;
ssl on;
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
ssl_prefer_server_ciphers on;
EOF
	cat> ${nginxpath}/conf/gzip.conf <<EOF
	#启用gzip压缩
    gzip  on;
	#设置允许压缩的页面最小字节数，页面字节数从header头中的Content-Length中进行获取。默认值是0，不管页面多大都压缩。
    gzip_min_length 1k;

	#设置系统获取几个单位的缓存用于存储gzip的压缩结果数据流。 例如 4 4k 代表以4k为单位，按照原始数据大小以4k为单位的4倍申请内存。 4 8k 代表以8k为单位，按照原始数据大小以8k为单位的4倍申请内存。
	#如果没有设置，默认值是申请跟原始数据相同大小的内存空间去存储gzip压缩结果
    gzip_buffers 4 16k;
	#识别http协议的版本
	gzip_http_version 1.1;
	#指定压缩比，1-9，等级越高压缩比例越高，但是也越消耗CPU资源
    gzip_comp_level 5;
	#压缩的格式
    gzip_types text/plain application/x-javascript text/css application/xml text/javascript;
	#让前端的缓存服务器缓存压缩后的页面
    gzip_vary on;
    gzip_proxied expired no-cache no-store private auth;
    gzip_disable "MSIE [1-6]\.";
EOF
	cat> ${nginxpath}/conf/fastcgi_cache.conf <<EOF
	#缓存目录，可以设置目录层级，比如1:2会生成16*256个字目录
 	fastcgi_cache_path /tmp/nginx_cache levels=1:2 keys_zone=cachephp:30m inactive=1d max_size=2g;

	#cache_php是这个缓存空间的名字
	fastcgi_cache_path ${nginxpath}/fastcgi_cache levels=1:2 keys_zone=TEST:10m inactive=5m; 
	fastcgi_cache_key "$request_method://$host$request_uri";
	fastcgi_connect_timeout 300; 
	fastcgi_send_timeout 300; 
	fastcgi_read_timeout 300; 
	fastcgi_buffer_size 64k; 
	fastcgi_buffers 4 64k; 
	fastcgi_busy_buffers_size 128k; 
	fastcgi_temp_file_write_size 128k; 
	fastcgi_cache TEST; 
	fastcgi_cache_valid 200 302 1h; 
	fastcgi_cache_valid 301 1d; 
	fastcgi_cache_valid any 1m;

	#定义哪些http头要缓存，后面是缓存的时间
	#fastcgi_cache_valid 200 302 1h;
	#fastcgi_cache_valid 301 1d;
	#fastcgi_cache_valid any 1m;

	#URL经过多少次请求将被缓存
 	fastcgi_cache_min_uses 1;
	fastcgi_cache_use_stale error timeout invalid_header http_500;

	# 打开文件描述符的文件大小和修改时间信息,脚本默认开启了10W
    open_file_cache max=100000 inactive=20s;

	#open_file_cache指令中的inactive参数时间内文件的最少使用次数，如果超过这个数字，文件描述符一直是在缓存中打开的。
    open_file_cache_min_uses 1;

	#这个是指多长时间检查一次缓存的有效信息。
    open_file_cache_valid 30s;


EOF
	cat> ${nginxpath}/conf/nginx.conf <<EOF
user  nginx nginx;
#worker进程数，cpu进程数-1
worker_processes  auto;

#cpu亲和力
worker_cpu_affinity auto;
#错误日志
error_log  logs/nginx_error.log;
pid        ${nginx_pid};
#worker打开的文件数，脚本默认10W
worker_rlimit_nofile 100000;
#关闭access日志
#access_log off;
events {
	#epoll模型
    use epoll;

	#worker最大连接数
    worker_connections  10240;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
	
	#隐藏X-Powered-By
	proxy_hide_header X-Powered-By;
 	#如果你的请求中的header都很大，那么应该使用client_header_buffer_size，这样能减少一次内存分配。
    client_header_buffer_size 32k;

	#如果你的请求中只有少量请求header很大，那么应该使用large_client_header_buffers，因为这样就仅需在处理大header时才会分配更多的空间，从而减少无谓的内存空间浪费。
    large_client_header_buffers 4 32k;
	#客户端上传文件的最大值
    client_max_body_size 500m;
    #能识别头文件的下划线
    underscores_in_headers      on;
	
	server_names_hash_max_size      2048;
    server_names_hash_bucket_size   512;
	#不能太大也不能太小，默认1k,提示以下错误才会增加
	#types_hash_max_size         4096

	#隐藏nginx的版本号 本脚本已经清空了tokens，不需要开启
	#server_tokens          off;

	#提高读写速度，开启sendfile就必须开启下面2项
    sendfile        on;
	# 较大的文件不要一次全读取了，浪费内存
    sendfile_max_chunk 512k;
    tcp_nopush     on;
    tcp_nodelay on;
	
	#设置客户端请求头读取超时时间
	client_header_timeout  10;
	#设置客户端请求主体读取超时时间 ，默认60秒
	client_body_timeout  10;
	#设置服务器响应客户端的超时时间
	send_timeout  10;
	#保持连接的时间，上传下载的时候能体现出来
	#解决方案将接口请求，后台管理，文件上传这三个业务逻辑分开，nginx对这三种业务逻辑分开转发，每个业务逻辑单独设置一个keepalive-timeout
    keepalive_timeout  60;
    #设置打开此创窗口缓存多长时间，根据网站更新的时间来设置
    #add_header Cache-Control "public, max-age=60";

    #########网站安全选项
	add_header Strict-Transport-Security max-age=86400;
	#add_header Access-Control-Allow-Origin "*";
	add_header 'Access-Control-Allow-Credentials' 'true'; 
	add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; 
	add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
	# 只允许本站用 frame 来嵌套
    add_header X-Frame-Options SAMEORIGIN;
    # 禁止嗅探文件类型
    add_header X-Content-Type-Options nosniff;
    # XSS 保护
    add_header X-XSS-Protection "1; mode=block";
	#同一ip的缓存区域
	limit_conn_zone \$binary_remote_addr zone=perip:10m; 
	#Robots
    add_header X-Robots-Tag none;
    #禁用浏览器打开下载的文件    
    add_header X-Download-Options noopen;
    #不允许跨域请求
    add_header X-Permitted-Cross-Domain-Policies none;

	#########后端真实服务器可以获取用户的ip
	#指定接收来自哪个前端发送的 IP head 可以是单个IP或者IP段，与后面的real_ip_header一起使用
    #set_real_ip_from 10.1.1.0/24;
	#IP head 的对应参数，默认即可。
    #real_ip_header    X-Forwarded-For;
    #real_ip_recursive on;

    #启用gzip压缩
    include gzip.conf;

    #开启php缓存，不是特别需要补建议开启
    #include fastcgi_cache.conf;

	#反向代理服务器proxy_pass，请打开此项
    #include proxy.conf;	
    include ${vhostdir}/*.conf;
}
stream {
	#支持tcp udp
	#支持access log
	#log_format main '\$remote_addr [\$time_local] '
    #             '\$protocol \$status \$bytes_sent \$bytes_received '
    #             '\$session_time "\$upstream_addr" '
    #             '"\$upstream_bytes_sent" "\$upstream_bytes_received" "\$upstream_connect_time"';
	include ${vhostdir}/*.pro;
}

EOF

cat> ${nginxpath}/conf/${vhostdir}/template.pro <<EOF
#upstream  test {
#    server 172.17.0.2:9999 weight=1;
#    server 172.17.0.2:9999 weight=1;
#}
#如果此端口与http的端口重复，不会报错，但是也不会生效，测试也无效，如果端口没监听到，查看是否与其他地方的端口有冲突
#server {
#    #listen 9999 udp;
#    listen 9999;
#	 access_log  logs/proxy.access.log main;
#	 error_log logs/proxy.error.log;
#    proxy_pass test;
#}
		
	

EOF

cat >${nginxpath}/conf/${vhostdir}/banip.conf <<EOF
#禁止ip访问，但是如果配置的server_name是ip，不会禁止
server {
    #listen 80;
    #server_name _;
    #return 404;
    #直接返回404不友好，建议重定向到主页
    #return 301 https://www.hyahm.com;
}
EOF

cat >${nginxpath}/conf/${vhostdir}/tohttps.conf <<EOF
#80端口301跳转到443端口参考配置
#server {
#    listen 80;
#    server_name test.com www.test.com;
#    return 301 https://www.test.com$request_uri;
#}
EOF
cat >${nginxpath}/conf/${vhostdir}/listdir.conf <<EOF
#这里是列出文件.目录的配置
#可以打开这个网站，就知道是什么东西了
#server {
#    listen       80;
#    server_name  download.hyahm.com;
#    charset utf8;
#    access_log  /data/log/download.access.log;
#    root /share;
#    error_log /data/log/download.error.log;

#    location / {
    	#列出文件和目录
#        autoindex on;
        #off是以易读的方式列出文件大小，on是b为大小列出
#        autoindex_exact_size off;
        #默认为off，显示的文件时间为GMT时间。改为on后，显示的文件时间为文件的服务器时间
#        autoindex_localtime on;
		#下载图片
#		 add_header Content-disposition "attachment;";
#    }

#}
EOF
	nginx
}

###########################################  end nginx  ##################################

#####################################   start postgresql   ##################################


function addposgresqluser {
	if [ ! -d ${postgresqlpath} ]
	then
		mkdir -p ${postgresqlpath}
	fi
	if [ ! -d ${postgresqldata} ]
	then
		mkdir -p ${postgresqldata}
	fi
	cat /etc/passwd  | grep "^${postgresqluser}:"
	if [ $? -ne 0 ]
	then
		useradd  ${postgresqluser}
	fi
	chown -R ${postgresqluser}:${postgresqluser} ${postgresqlpath}
	
	chown -R ${postgresqluser}:${postgresqluser} ${postgresqldata}
	
	#配置环境变量
	#讲命令添加到启动项

		grep "PATH=\$PATH:${postgresqlpath}/bin" /etc/profile
		if [ $? -ne 0 ]
		then
		        echo "export PATH=\$PATH:${postgresqlpath}/bin" >> /etc/profile
		        #启动数据库目录，配置后启动的时候会省掉-D选项
		        echo "export PGDATA=${postgresqldata}"  >> /etc/profile		        
		fi
		source /etc/profile

}

function postgresqldepend {
	yum -y install bzip2 gcc systemtap-sdt-devel.x86_64  perl-ExtUtils-Embed readline-devel zlib-devel openssl-devel   pam-devel libxml2-devel  libxslt-devel  openldap-devel  tcl-devel  python-devel  uuid-devel

}

function downloadpostgresql {
	cd
	if [ ! -d  /usr/local/src/${postgresqlversion} ]
	then
		rm -f ${postgresqlversion}.tar.bz2
		wget https://ftp.postgresql.org/pub/source/v${downloadpathdir}/${postgresqlversion}.tar.bz2
		tar -xf ${postgresqlversion}.tar.bz2 -C /usr/local/src
	fi
}

function installpostgresql {
	cd /usr/local/src/${postgresqlversion}	
	if [ ${version} -eq 7 ]
	then
		./configure --prefix=${postgresqlpath} --with-blocksize=8  --with-perl --with-python --with-tcl --with-openssl --with-pam --with-ldap --with-libxml --with-selinux --with-libxslt --with-uuid=ossp --enable-thread-safety --enable-dtrace
	else
		./configure --prefix=${postgresqlpath} --with-blocksize=8  --with-perl --with-python --with-tcl --with-openssl --with-pam --with-ldap --with-libxml --with-libxslt --with-uuid=ossp --enable-thread-safety --enable-dtrace
	fi
	
	if [ $? -ne 0 ]
	then
		echo "编译错误"
		exit 1
	fi
	make -j ${cpunu}
	make install
	cd contrib/uuid-ossp/	
	make && make install
	cd ..
	make && make install
	su ${postgresqluser} -c  "initdb -D ${postgresqldata}  -U ${postgresqluser}"
	chown -R ${postgresqluser}:${postgresqluser} ${postgresqlpath}
	
	chown -R ${postgresqluser}:${postgresqluser} ${postgresqldata}
	mkdir /var/run/postgresql
	chown -R ${postgresqluser}:${postgresqluser} /var/run/postgresql
	cp /usr/local/src/${postgresqlversion}/contrib/start-scripts/linux /etc/init.d/${postgresqlservername}
	#添加执行权限
	chmod +x /etc/init.d/${postgresqlservername}
	sed -i "s#prefix=\/usr\/local\/pgsql#prefix=${postgresqlpath}#" /etc/init.d/${postgresqlservername}
	sed -i "s#\/usr\/local\/pgsql\/data#${postgresqldata}#" /etc/init.d/${postgresqlservername}
	sed -i "s/PGUSER=postgres/PGUSER=${postgresqluser}/" /etc/init.d/${postgresqlservername}
	
}

function postgresqlyouhua {
	sharemem=`expr ${memsize} / 4`
	effectivemem=`expr ${memsize} / 3`
	sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/" ${postgresqldata}/postgresql.conf
	sed -i "s/#random_page_cost = 4.0/#random_page_cost = 2.0/" ${postgresqldata}/postgresql.conf
	sed -i "s/shared_buffers = 128MB/shared_buffers = ${sharemem}MB/" ${postgresqldata}/postgresql.conf
	sed -i "s/#effective_cache_size = 4GB/effective_cache_size = ${effectivemem}MB/" ${postgresqldata}/postgresql.conf
	echo "shared_preload_libraries = 'pg_stat_statements'" >> ${postgresqldata}/postgresql.conf
	echo "pg_stat_statements.max = 10000"  >> ${postgresqldata}/postgresql.conf
	echo "pg_stat_statements.track = all" >> ${postgresqldata}/postgresql.conf
}

function startpostgresql {
	su ${postgresqluser} -c "pg_ctl start"

	        cat > /etc/init.d/${postgresqlservername}  <<EOF
#!\/bin\/sh
# chkconfig: 2345 98 02
prefix=${postgresqlpath}
PGDATA=${postgresqldata}
PGUSER=${postgresqluser}
PGCTL="\$prefix/bin/pg_ctl"
case \$1 in
  start)
    echo -n "Starting PostgreSQL: "
    su - \$PGUSER -c "\$PGCTL start "
    echo "ok"
    ;;
  stop)
    echo -n "Stopping PostgreSQL: "
    su - \$PGUSER -c "\$PGCTL stop "
    echo "ok"
    ;;
  restart)
    echo -n "Restarting PostgreSQL: "
    su - \$PGUSER -c "\$PGCTL stop "
    su - \$PGUSER -c "\$PGCTL start "
    echo "ok"
    ;;
  reload)
    echo -n "Reload PostgreSQL: "
    su - \$PGUSER -c "\$PGCTL reload"
    echo "ok"
    ;;
  status)
    su - \$PGUSER -c "\$PGCTL status"
    ;;
  *)
    echo "Usage: \$0 {start|stop|restart|reload|status}" 1>&2
    exit 1
    ;;
esac

exit 0
EOF

chkconfig --add ${postgresqlservername}
chkconfig ${postgresqlservername} on

}
########################################   end postgresql    ########################################

############################################   start mysql #########################################

function mysqldepend {
	yum -y install gcc-c++  ncurses-devel cmake libtirpc-devel rpcgen
	#增加swap分区
	swap=`free -m | grep Swap | awk '{print $2}'`
	if [ ${swap} -lt 500 ]
	then
		dd  if=/dev/zero of=/swapfile bs=1k count=1024000
		mkswap  /swapfile
		swapon  /swapfile
		echo "/swapfile  swap swap defaults 0 0" >> /etc/fstab
		mount  -a
	fi
}

function mysqldependcentos9 { 
	yum -y install gcc-c++  ncurses-devel cmake rpcgen  openssl-devel gcc-toolset-12-gcc gcc-toolset-12-gcc-c++ gcc-toolset-12-binutils gcc-toolset-12-annobin-annocheck gcc-toolset-12-annobin-plugin-gcc
	# 单独安装 
	dnf -y install https://mirrors.tuna.tsinghua.edu.cn/centos-stream/9-stream/CRB/x86_64/os/Packages/libtirpc-devel-1.3.3-9.el9.x86_64.rpm
	#增加swap分区
	swap=`free -m | grep Swap | awk '{print $2}'`
	if [ ${swap} -lt 500 ]
	then
		dd  if=/dev/zero of=/swapfile bs=1k count=1024000
		mkswap  /swapfile
		swapon  /swapfile
		echo "/swapfile  swap swap defaults 0 0" >> /etc/fstab
		mount  -a
	fi
}

function getmysql {

	if [ ! -d /usr/local/src/${mysql} ]
	then

		cd
		rm -f  ${mysqldown}.tar.gz
		#有些宽带无法下载,只支持5.7.17版
		
		wget -O /root/${mysql}.tar.gz https://cdn.mysql.com//Downloads/MySQL-${mysqlv}/${mysqldown}.tar.gz 
		if  [ $? -ne 0  ]
		then
			echo "下载mysql失败，请重新执行脚本，或者下载对应版本解压到/usr/local/src下可以跳过"
			exit 1
		fi
		tar -xf ${mysql}.tar.gz  -C  /usr/local/src/ 
	fi
}

function installmysql7 {
if [ ! -d ${mysqlpath} ]
then
	mkdir -p ${mysqlpath}
fi
cd /usr/local/src/${mysql}

if [ "${mysqlv}" = "5.7" ]
then
	cmake . -DCMAKE_INSTALL_PREFIX=${mysqlpath} -DWITH_BOOST=/usr/local/src/${mysql}/boost \
    	-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
    	-DEVHTP_DISABLE_SSL=ON \
    	-DEVHTP_BUILD_SHARED=OFF \
    	-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
    	-DWITH_PERFSCHEMA_STORAGE_ENGINE=1 \
		-DDEFAULT_CHARSET=utf8  \
		-DWITH_SYSTEMD=ON \
    	-DDEFAULT_COLLATION=utf8_general_ci
    	if [ $? -ne 0 ]
		then
			exit 1
		fi
	#编译mysql，如果cpu设置太高会导致内存的大量消耗，如果配置高可开启
	#make -j ${cpunu} && make install
	if [ ${tofast} -eq 1 ]
	then	
		make -j ${cpunu} && make install
	else
		make && make install
	fi
    cat >/etc/systemd/system/mysqld.service <<EOF
    [Unit]
Description=MySQL Server
Documentation=man:mysqld(8)
Documentation=http://dev.mysql.com/doc/refman/en/using-systemd.html
After=network.target
After=syslog.target

[Install]
WantedBy=multi-user.target

[Service]
User=${mysqluser}
Group=${mysqluser}
Type=forking
PIDFile=/tmp/mysqld.pid
# Disable service start and stop timeout logic of systemd for mysqld service.
TimeoutSec=0
# Execute pre and post scripts as root
PermissionsStartOnly=true
# Needed to create system tables
ExecStartPre=${mysqlpath}/bin/mysqld_pre_systemd
# Start main service
ExecStart=${mysqlpath}/bin/mysqld --daemonize --pid-file=/tmp/mysqld.pid \$MYSQLD_OPTS
# Use this to switch malloc implementation
EnvironmentFile=-/etc/sysconfig/mysql
# Sets open_files_limit
LimitNOFILE = 5000
Restart=on-failure
RestartPreventExitStatus=1
PrivateTmp=false
EOF
else
	cmake . -DCMAKE_INSTALL_PREFIX=${mysqlpath}  \
    	-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
    	-DEVHTP_DISABLE_SSL=ON \
    	-DEVHTP_BUILD_SHARED=OFF \
    	-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
    	-DWITH_PERFSCHEMA_STORAGE_ENGINE=1 \
		-DDEFAULT_CHARSET=utf8  \
		-DWITH_SYSTEMD=ON \
    	-DDEFAULT_COLLATION=utf8_general_ci
    	if [ $? -ne 0 ]
		then
			exit 1
		fi
	#编译mysql，如果cpu设置太高会导致内存的大量消耗，如果配置高可开启
	#make -j ${cpunu} && make install
	if [ ${tofast} -eq 1 ]
	then	
		make -j ${cpunu} && make install
	else
		make && make install
	fi
    
    cp support-files/mysql.server /etc/init.d/mysqld
	sed -i "46s#basedir=#basedir=${mysqlpath}#" /etc/init.d/mysqld
    sed -i "47s#datadir=#datadir=${mysqldata}#" /etc/init.d/mysqld
	sed -i "214s#  conf=/etc/my.cnf#  conf=${mysql_config_file}#" /etc/init.d/mysqld
	chmod +x /etc/init.d/mysqld

fi
}

function installmysql {
if [ ! -d ${mysqlpath} ]
then
    mkdir -p ${mysqlpath}
fi
cd /usr/local/src/${mysql}
if [[ "${mysqlv}" = "5.7" ]]; then
	#statements

    cmake . -DCMAKE_INSTALL_PREFIX=${mysqlpath} -DWITH_BOOST=/usr/local/src/${mysql}/boost \
        -DWITH_ARCHIVE_STORAGE_ENGINE=1 \
        -DEVHTP_DISABLE_SSL=ON \
        -DEVHTP_BUILD_SHARED=OFF \
        -DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
        -DWITH_PERFSCHEMA_STORAGE_ENGINE=1 \
        -DDEFAULT_CHARSET=utf8  \
		-DMYSQLX_UNIX_ADDR=${mysqlsock} \
        -DDEFAULT_COLLATION=utf8_general_ci
        if [ $? -ne 0 ]
        then
            exit 1
        fi
    #编译mysql，如果cpu设置太高会导致内存的大量消耗，如果配置高可开启
    #make -j ${cpunu} && make install
    if [ ${tofast} -eq 1 ]
    then
        make -j ${cpunu} && make install
    else
        make && make install
    fi
else
	cmake . -DCMAKE_INSTALL_PREFIX=${mysqlpath}  \
        -DWITH_ARCHIVE_STORAGE_ENGINE=1 \
        -DEVHTP_DISABLE_SSL=ON \
        -DEVHTP_BUILD_SHARED=OFF \
        -DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
        -DWITH_PERFSCHEMA_STORAGE_ENGINE=1 \
        -DDEFAULT_CHARSET=utf8  \
		-DMYSQLX_UNIX_ADDR=${mysqlsock} \
        -DDEFAULT_COLLATION=utf8_general_ci
        if [ $? -ne 0 ]
        then
            exit 1
        fi
    #编译mysql，如果cpu设置太高会导致内存的大量消耗，如果配置高可开启
    #make -j ${cpunu} && make install
    if [ ${tofast} -eq 1 ]
    then
        make -j ${cpunu} && make install
    else
        make && make install
    fi

fi
if [ -f /etc/init.d/mysqld  ]
then
	rm -f /etc/init.d/mysqld
fi
cp support-files/mysql.server /etc/init.d/mysqld
sed -i "46s#basedir=#basedir=${mysqlpath}#" /etc/init.d/mysmysqldql
sed -i "47s#datadir=#datadir=${mysqldata}#" /etc/init.d/mysqld
sed -i "214s#  conf=/etc/my.cnf#  conf=${mysql_config_file}#" /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld
}
function mysqluser {
	cat /etc/passwd | grep "^${mysqluser}:"
	if [ $? -ne 0 ]
	then
		groupadd ${mysqluser}
		useradd -g ${mysqluser} -M -s /sbin/nologin ${mysqluser}
	fi
}

function mysqlsetting() {
	cd /usr/local/src/${mysql}
	ln -s ${mysqlpath}/bin/*  /bin
	mkdir /var/log/mysql
	chown -R ${mysqluser}:${mysqluser} /var/log/mysql
	if [ ! -d ${mysqldata} ];then
		mkdir -p ${mysqldata}
	fi
	chown -R ${mysqluser}:${mysqluser} ${mysqldata}
	if [ "${mysqlv}" = "5.7" ];then

		if [ -f /root/.m.txt ]
		then
			rm -f /root/.m.txt
		fi

		mysqld --initialize  --user=${mysqluser}  --basedir=${mysqlpath}  --datadir=${mysqldata} &> /root/.m.txt
	else
		chmod +x /usr/local/src/${mysql}/scripts/mysql_install_db
		/usr/local/src/${mysql}/scripts/mysql_install_db --basedir=${mysqlpath} --datadir=${mysqldata} --user=${mysqluser}
	fi
	if [ ! -f /usr/lib64/libmysqlclient.so.18 ];then
		cp -f /usr/local/src/${mysql}/libmysql/* /usr/lib64/
	fi
	mysqlmem=`expr ${memsize} / 2`
	grep "net.ipv4.tcp_fin_timeout = 30" /etc/sysctl.conf
	#防止mysql进程卡死	
	if [ $? -eq 0 ]
	then
		cat >> /etc/sysctl.conf <<EOF
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 30	
EOF
	sysctl -p
	fi

	cat>${mysql_config_file}<<EOF
[client]
user=root
password='${rootpwd}'
[mysqld]

#忘记root密码，开启此处重启服务后可以直接进入数据库
#skip-grant-tables
  
basedir =${mysqlpath}  
datadir = ${mysqldata}
port=3306
#server_id = .....
socket =${mysqlsock}
  
#关闭名称解析,虽然可以加快连接速度库的速度，但是同时也禁止了root账号使用 -h登录
#skip-name-resolve = ON

#开启二进制日志，且指定日志前缀名
#log-bin = mysql-bin
#设置默认的字符集为utf8，新建数据库继承此属性
character_set_server = utf8

#MySql的随机读（查询操作）缓冲区大小
read_rnd_buffer_size = 100M
#批量插入数据缓存大小，可以有效提高插入效率，默认为8M
bulk_insert_buffer_size = 20M
#索引缓存大小: 它决定了数据库索引处理的速度，尤其是索引读的速度
key_buffer_size = 2M
#发生变化时重新排序所需的缓冲
sort_buffer_size = 8M
#用于表间关联缓存的大小
join_buffer_size = 4M

#允许的最大连接数 
max_connections = 1024 
#默认值1M，控制通信缓冲区的最大长度，SQL语句过大或者语句中含有BLOB或者longblob字段时，默认的缓冲可能不够
max_allowed_packet = 20M
#是否启用查询缓存
query_cache_type = ON
#不缓存大于此大小的结果，默认1M
query_cache_limit = 2M
#定义查询缓存所使用的内存大小
query_cache_size = 120M

#启用慢日志
slow_query_log = ON
#定义慢日志的存放路径
slow-query-log-file = /var/log/mysql/slow.log
#定义大于多少秒的查询纪录慢日志
long_query_time = 1

#设置innodb每表独立的表空间
innodb_file_per_table = 1
#innodb可以使用的数据和索引cashe的总大小，默认128M，对于innodb来说，调大此参数可以极大提高性能,内存的60-70%
innodb_buffer_pool_size = ${mysqlmem}M
#innodb buffer pool会分割成多少个instance存储，提高并发性
innodb_buffer_pool_instances = 4
#opzition
performance_schema=ON

#myisam索引的缓存大小
key_buffer_size = 1M
#保存在内存中的临时表的大小限制，group by操作优化
tmp_table_size = 20M
#内存表的大小限制
max_heap_table_size = 10M

#提高包的大小限制
max_allowed_packet = 500M
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
#需要添加以下内容
[mysqld_safe]    
#创建日志文件
log-error=/var/log/mysqld.log    
#创建pid文件
pid-file=/var/run/mysqld/mysqld.pid 
EOF
if [ "${mysqlv}" = "5.7" ]
then
	echo "5.7"
else 	
	
	sed -i 's/user=root/#user=root/' ${mysql_config_file}
	sed -i 's/password=/#password=/' ${mysql_config_file}
fi

chmod 644 ${mysql_config_file}
chown -R ${mysqluser}:${mysqluser} /var/log/mysql
}

function upmysql {
	if [ "${version}" = "7" ]
	then
		systemctl enable mysqld
	else
		chkconfig --add mysqld
		chkconfig mysqld on
	fi
	
	if [ "${mysqlv}" = "5.7" ]
	then
		mysqltmppassword=`cat /root/.m.txt | grep -v "^$" | tail -1 | awk '{print $NF}'`

		chpwd="mysqladmin -u root -p'${mysqltmppassword}' password ${rootpwd}"
		eval $chpwd
	else 
		mysqladmin  password "${rootpwd}"
		mysqladmin  password "${rootpwd}"
		
		sed -i 's/#user=root/user=root/' ${mysql_config_file}
		sed -i 's/#password=/password=/' ${mysql_config_file}
	fi
	mysqld --defaults-file=${mysql_config_file} --user=${mysqluser}
	echo "$password" > /root/.m.txt
}

###########################################    end mysql   ##########################################

######################################    start php   ##############################

function getphp {
	if [ ! -d /usr/local/src/${phpversion} ]
	then
		cd
		if [ ! -f /root/${phpversion}.tar.gz ];then
			wget -O /root/${phpversion}.tar.gz   http://cn2.php.net/distributions/${phpversion}.tar.gz
			if [ $? -ne 0 ]
			then
				echo "下载php失败"
				exit 1
			fi
		fi
		tar -xf ${phpversion}.tar.gz   -C /usr/local/src
	fi
	
	
}

function phpdepend {
	if [ ! -d ${phppath}  ]
	then
		mkdir -p ${phppath}
	fi
	if [ ! -d ${phpconfig} ]
	then
		mkdir -p ${phpconfig}
	fi
	
	yum -y install libevent libicu-devel  libxml2-devel  libjpeg-devel  libpng-devel  freetype-devel  zlib-devel  gcc   libmcrypt-devel autoconf libcurl-devel unzip openssl-devel ca-certificates libzip libzip-devel openldap-devel postgresql-devel  gcc-c++
	if [ $? -ne 0 ]
	then
		echo "安装php依赖失败"
		exit 1
	fi
	yum -y install systemtap-sdt-devel 
	if [ $? -ne 0 ]
	then
		echo "安装systemtap-sdt-devel失败"
		exit 1
	fi
	cp /usr/lib64/libldap* /usr/lib/
}

function install_libiconv {
	if [ ! -d /usr/local/libiconv ]
	then
		wget download.hyahm.com/libiconv-1.15.tar.gz
		tar -xf libiconv-1.15.tar.gz -C /usr/local/src
		cd  /usr/local/src/libiconv-1.15
		./configure --prefix=/usr/local/libiconv
		if [ $? -ne 0 ]
		then
			echo "编译libiconv错误"
			exit 1
		fi
		make -j ${cpunu}
		make install
	else
		echo "存在libiconv,已跳过"
	fi
}


function installphp {	
	cd   /usr/local/src/${phpversion}
	make clean
	rm -f Makefile
	./configure --prefix=${phppath}  --enable-intl  --enable-zip --enable-exif --with-iconv-dir=/usr/local/libiconv  --enable-pcntl  --enable-dtrace  --enable-sysvsem --enable-ftp  --enable-soap --enable-shmop --with-ldap --enable-fpm   --with-config-file-path=${phpconfig}  --with-png-dir --enable-mysqlnd  --with-mysql=mysqlnd  --with-pdo-mysql=mysqlnd  --with-mysqli=mysqlnd --enable-bcmath --enable-mbstring --enable-sockets --with-gd --with-jpeg-dir --with-freetype-dir --with-gettext  --with-zlib --enable-opcache --with-mcrypt --with-xmlrpc --with-openssl --with-curl 
	phplinshi=`grep "EXTRA_LIBS = " Makefile`
	sed -i "s/${phplinshi}/${phplinshi}  -llber  -lstdc++  /" Makefile
	php_ext_dir=`cat Makefile | grep "EXTENSION_DIR =" | awk '{print $3}'`
	make -j ${cpunu}
	if [ $? -ne 0 ]
		then
			echo "编译php5错误"
			exit 1
	fi
	make install
}

function installphp7 {
	cd   /usr/local/src/${phpversion}
	make clean
	rm -f Makefile
	./configure --prefix=${phppath} --enable-intl --enable-zip --enable-pcntl --enable-exif   --with-iconv-dir=/usr/local/libiconv  --enable-dtrace  --enable-sysvsem --enable-ftp  --enable-soap --enable-shmop  --with-ldap --enable-fpm   --with-config-file-path=${phpconfig}  --with-png-dir --enable-mysqlnd    --with-pdo-mysql=mysqlnd  --with-mysqli=mysqlnd --enable-bcmath --enable-mbstring --enable-sockets --with-gd --with-jpeg-dir --with-freetype-dir --with-gettext  --with-zlib --enable-opcache --with-mcrypt --with-xmlrpc --with-openssl --with-curl
	phplinshi=`grep "EXTRA_LIBS = " Makefile`
	if [ "${phpnu}" = "7" ];then
		sed -i "s/${phplinshi}/${phplinshi}  -llber /" Makefile
	else		
		sed -i "s/${phplinshi}/${phplinshi}  -llber -liconv /" Makefile
	fi

	php_ext_dir=`cat Makefile | grep "EXTENSION_DIR =" | awk '{print $3}'`	
	make -j ${cpunu} 
	if [ $? -ne 0 ]
		then
			echo "编译php7错误"
			exit 1
	fi
	make install
}
function phpconfig {
	mkdir -p ${phplog}
	#添加环境变量
	grep "export PATH=\$PATH:${phppath}/bin/" /etc/bashrc
	if [ $? -ne 0  ]
	then
		echo "export PATH=\$PATH:${phppath}/bin/" >>  /etc/bashrc 
		source /etc/bashrc
	fi
	if [ -f ${phppath}/etc/php-fpm.conf ]
	then
		rm -f  ${phppath}/etc/php-fpm.conf
	fi
	cp  ${phppath}/etc/php-fpm.conf.default  ${phppath}/etc/php-fpm.conf
	if [ ! -f ${phpconfig}/php.ini ]
		then
			cp /usr/local/src/${phpversion}/php.ini-development ${phpconfig}/php.ini
		fi
	if [  ${phpnum} -eq 7 ]
	then		
		if [ ! -f ${phppath}/etc/php-fpm.d/www.conf ]
		then
			cp  ${phppath}/etc/php-fpm.d/www.conf.default  ${phppath}/etc/php-fpm.d/www.conf
		fi
		#创建错误日志目录
		if [ ! -d ${php_err_log} ]
		then
			mkdir -p ${php_err_log}
		fi
		grep ${phpuser} /etc/passwd	
		if [  $? -eq 0 ]
		then	
			sed -i "s/user = nobody/user = ${phpuser}/"  ${phppath}/etc/php-fpm.d/www.conf
			sed -i "s/group = nobody/group = ${phpuser}/"  ${phppath}/etc/php-fpm.d/www.conf
		fi
		sed -i "s/9000/${phpport}/" ${phppath}/etc/php-fpm.d/www.conf
		sed -i 's/pm.max_children = 5/pm.max_children = 500/'  ${phppath}/etc/php-fpm.d/www.conf
		sed -i 's/;pm.max_requests = 500/pm.max_requests = 1000/'  ${phppath}/etc/php-fpm.d/www.conf		
		sed -i "s#;slowlog = log\/\$pool.log.slow#slowlog = ${phplog}\/slow.log#"  ${phppath}/etc/php-fpm.d/www.conf	
		sed -i 's/;request_slowlog_timeout = 0/request_slowlog_timeout = 3/'  ${phppath}/etc/php-fpm.d/www.conf
		sed -i "s#;php_admin_value\[error_log\] = \/var\/log\/fpm-php.www.log#php_admin_value\[error_log\] = ${php_err_log}\/php_err.log#" /usr/local/etc/php-fpm.d/www.conf
	else
		grep ${phpuser} /etc/passwd	
		if [  $? -eq 0 ]
		then	
			sed -i "s/user = nobody/user = ${phpuser}/"  ${phppath}/etc/php-fpm.conf
			sed -i "s/group = nobody/group = ${phpuser}/"  ${phppath}/etc/php-fpm.conf
		fi
		sed -i "s/9000/${phpport}/" ${phppath}/etc/php-fpm.conf
		sed -i 's/user = nobody/user = nginx/'  ${phppath}/etc/php-fpm.conf
		sed -i 's/group = nobody/group = nginx/'  ${phppath}/etc/php-fpm.conf
		sed -i 's/pm.max_children = 5/pm.max_children = 500/'  ${phppath}/etc/php-fpm.conf
		sed -i 's/;pm.max_requests = 500/pm.max_requests = 1000/'  ${phppath}/etc/php-fpm.conf		
		sed -i "s#;slowlog = log\/\$pool.log.slow#slowlog = ${phplog}\/slow.log#"  ${phppath}/etc/php-fpm.conf	
		sed -i 's/;request_slowlog_timeout = 0/request_slowlog_timeout = 3/'  ${phppath}/etc/php-fpm.conf	
	fi
		
	
	
	if [ ${version} -eq 7 ]
	then
		cat>/usr/lib/systemd/system/php-fpm.service<<EOF
[Unit]
Description=The PHP FastCGI Process Manager
After=syslog.target network.target

[Service]
Type=simple
PIDFile=/var/run/php-fpm.pid
ExecStart=${phppath}/sbin/php-fpm --nodaemonize --fpm-config ${phppath}/etc/php-fpm.conf
ExecReload=/bin/kill -USR2 \$MAINPID

[Install]
WantedBy=multi-user.target
EOF
	else		
		cat>/etc/init.d/php-fpm <<"EOF"
#!/bin/sh
### BEGIN INIT INFO
# Provides:          php-fpm
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts php-fpm
# Description:       starts the PHP FastCGI Process Manager daemon
### END INIT INFO

prefix=tttttt
exec_prefix=${prefix}

php_fpm_BIN=${exec_prefix}/sbin/php-fpm
php_fpm_CONF=${prefix}/etc/php-fpm.conf
php_fpm_PID=${prefix}/var/run/php-fpm.pid


php_opts="--fpm-config $php_fpm_CONF --pid $php_fpm_PID"


wait_for_pid () {
	try=0

	while test $try -lt 35 ; do

		case "$1" in
			'created')
			if [ -f "$2" ] ; then
				try=''
				break
			fi
			;;

			'removed')
			if [ ! -f "$2" ] ; then
				try=''
				break
			fi
			;;
		esac

		echo -n .
		try=`expr $try + 1`
		sleep 1

	done

}

case "$1" in
	start)
		echo -n "Starting php-fpm "

		$php_fpm_BIN --daemonize $php_opts

		if [ "$?" != 0 ] ; then
			echo " failed"
			exit 1
		fi

		wait_for_pid created $php_fpm_PID

		if [ -n "$try" ] ; then
			echo " failed"
			exit 1
		else
			echo " done"
		fi
	;;

	stop)
		echo -n "Gracefully shutting down php-fpm "

		if [ ! -r $php_fpm_PID ] ; then
			echo "warning, no pid file found - php-fpm is not running ?"
			exit 1
		fi

		kill -QUIT `cat $php_fpm_PID`

		wait_for_pid removed $php_fpm_PID

		if [ -n "$try" ] ; then
			echo " failed. Use force-quit"
			exit 1
		else
			echo " done"
		fi
	;;

	status)
		if [ ! -r $php_fpm_PID ] ; then
			echo "php-fpm is stopped"
			exit 0
		fi

		PID=`cat $php_fpm_PID`
		if ps -p $PID | grep -q $PID; then
			echo "php-fpm (pid $PID) is running..."
		else
			echo "php-fpm dead but pid file exists"
		fi
	;;

	force-quit)
		echo -n "Terminating php-fpm "

		if [ ! -r $php_fpm_PID ] ; then
			echo "warning, no pid file found - php-fpm is not running ?"
			exit 1
		fi

		kill -TERM `cat $php_fpm_PID`

		wait_for_pid removed $php_fpm_PID

		if [ -n "$try" ] ; then
			echo " failed"
			exit 1
		else
			echo " done"
		fi
	;;

	restart)
		$0 stop
		$0 start
	;;

	reload)

		echo -n "Reload service php-fpm "

		if [ ! -r $php_fpm_PID ] ; then
			echo "warning, no pid file found - php-fpm is not running ?"
			exit 1
		fi

		kill -USR2 `cat $php_fpm_PID`

		echo " done"
	;;

	configtest)
		$php_fpm_BIN -t
	;;

	*)
		echo "Usage: $0 {start|stop|force-quit|restart|reload|status|configtest}"
		exit 1
	;;

esac
EOF
	sed -i "s#tttttt#${phppath}#" /etc/init.d/php-fpm
	chmod 755 /etc/init.d/php-fpm
	fi
}

function phpmongodb {
	cd /usr/local/src
	rm -fr mongo-php-driver
	git clone https://github.com/mongodb/mongo-php-driver.git
	if [ $? -ne 0 ]
	then
		yum update -y nss curl libcurl  
		git clone https://github.com/mongodb/mongo-php-driver.git
	fi
	cd mongo-php-driver
	git submodule sync && git submodule update --init
	phpize
	./configure --with-php-config=${phppath}/bin/php-config
	make 
	if [ $? -ne 0 ]
        then
            echo "编译phpmongo错误"
            exit 1
    fi
	make install

	grep "mongodb.so" ${phpconfig}/php.ini
    if [ $? -ne 0  ]
    then
    cat>>${phpconfig}/php.ini<<EOF
extension="mongodb.so"
EOF
fi
}

function phpredis {
	cd /usr/local/src
	if [ ! -d /usr/local/src/redis-3.1.4.tgz ]
	then
		wget -O /usr/local/src/redis-3.1.4.tgz  http://pecl.php.net/get/redis-3.1.4.tgz	
	else
		rm -f /usr/local/src/redis-3.1.4.tgz
	fi	
	tar -xf redis-3.1.4.tgz -C /usr/local/src/
	cd /usr/local/src/redis-3.1.4
	phpize
	./configure --with-php-config=${phppath}/bin/php-config
	if [ $? -ne 0 ]
	then
		echo "编译phpredis错误"
		exit 1
	fi
	make -j ${cpunu} && make install
	
	grep "${php_ext_dir}/redis.so" ${phpconfig}/php.ini
    if [ $? -ne 0  ]
	then
	cat>>${phpconfig}/php.ini<<EOF
[redis]
extension_dir="${php_ext_dir}"
extension="redis.so"
EOF
	fi

}

# swoole 1.9版本
function phpswoole {
	cd /usr/local/src

	if  [ ! -d /usr/local/src/swoole-1.9.15 ]
	then
		wget http://pecl.php.net/get/swoole-1.9.15.tgz
	else 
		rm -fr swoole-1.9.15
	fi 
	tar -xf swoole-1.9.15.tgz -C /usr/local/src
	cd  swoole-1.9.15/
	phpize
	./configure --with-php-config=${phppath}/bin/php-config
	if [ $? -ne 0 ]
	then
		echo "编译swoole1错误"
		exit 1
	fi
	make  -j ${cpunu}
	make install
	grep "${php_ext_dir}/swoole.so" ${phpconfig}/php.ini
	if [ $? -ne 0 ]
	then
		echo "extension=${php_ext_dir}/swoole.so" >> ${phpconfig}/php.ini
	fi


}

# swoole 2.0.7版本
function phpswoole2 {
	
	if [ ! -f ${php_ext_dir}/swoole.so ]
	then
		if  [ ! -d /usr/local/src/swoole ]
		then
			cd /usr/local/src
			git clone  https://git.oschina.net/swoole/swoole.git			
			if [  $? -ne 0 ]; then
				yum update -y nss curl libcurl   
				git clone  https://git.oschina.net/swoole/swoole.git
			fi
		fi 
		cd  /usr/local/src/swoole/
		phpize
		./configure --with-php-config=${phppath}/bin/php-config  --enable-coroutine
		if [ $? -ne 0 ]
		then
			echo "编译swoole2错误"
			exit 1
		fi
		make  -j ${cpunu}
		make install
		grep "${php_ext_dir}/swoole.so" ${phpconfig}/php.ini
		if [ $? -ne 0 ]
		then
			echo "extension=${php_ext_dir}/swoole.so" >> ${phpconfig}/php.ini
		fi
	else
		echo "存在swoole.so,已跳过安装"
	fi

}

#postgrepsql拓展
function phppostgresql {
	if [ ! -f ${php_ext_dir}/pdo_pgsql.so ]
	then
		cd /usr/local/src/${phpversion}/ext/pdo_pgsql
		phpize
		./configure --with-php-config=${phppath}/bin/php-config
		if [ $? -ne 0 ]
		then
			echo "编译phppg错误"
			exit 1
		fi
		make  -j ${cpunu}
		make install
		grep "${php_ext_dir}/pdo_pgsql.so" ${phpconfig}/php.ini
		if [ $? -ne 0 ]
		then
			echo "extension=${php_ext_dir}/pdo_pgsql.so" >> ${phpconfig}/php.ini
		fi
	else
		echo "存在pdo_pgsql.so,已跳过安装"
	fi
}

# 源下载地址   ftp://ftp.u-aizu.ac.jp/pub/graphics/image/ImageMagick/imagemagick.org
#如果要更换版本，请修改完整路径
function  phpimageick {
	if [ ! -f  ${php_ext_dir}/imagick.so ]
	then
		yum -y install libtool-ltdl libtool-ltdl-devel
		cd
		if [ ! -d /usr/local/src/ImageMagick-7.0.5-0 ]
		then
			rm -f ImageMagick-7.0.5-0.tar.xz
			wget http://download.hyahm.com/ImageMagick-7.0.5-0.tar.xz
			tar -xf ImageMagick-7.0.5-0.tar.xz -C /usr/local/src
		fi
		cd  /usr/local/src/ImageMagick-7.0.5-0
		./configure -prefix=/usr/local/imagemagick -enable-lzw -with-modules 
		if [ $? -ne 0 ]
		then
			echo "编译错误"
			exit 1
		fi
		make  -j ${cpunu} && make install

	#下载的地址   http://pecl.php.net/package/imagick
	#如果要更换版本，请修改完整路径
		cd
		if [ ! -d /usr/local/src/imagick-3.4.3 ]
		then
			rm -f imagick-3.4.3.tgz
			wget  http://pecl.php.net/get/imagick-3.4.3.tgz
			tar -xf imagick-3.4.3.tgz -C /usr/local/src
		fi
		cd  /usr/local/src/imagick-3.4.3
		phpize
		./configure --with-php-config=${phppath}/bin/php-config --with-imagick=/usr/local/imagemagick
		if [ $? -ne 0 ]
		then
			echo "编译错误"
			exit 1
		fi
		make -j ${cpunu} && make install
		grep  "${php_ext_dir}/imagick.so"  ${phpconfig}/php.ini
		if  [ $? -ne 0 ]
		then
			echo "extension=${php_ext_dir}/imagick.so" >>  ${phpconfig}/php.ini
		fi
	else
		echo "存在imagick.so,已跳过安装"
	fi
}

#memcached 拓展
function phpmemcached {
	if [ ! -f ${php_ext_dir}/memcached.so ]
	then
		#编译安装 memcached 依赖的 libevent 库
		cd 
		#if [ ! -f libevent-2.1.8-stable.tar.gz ]
		#then
	#		wget http://download.hyahm.com/libevent-2.1.8-stable.tar.gz
#		fi
#		tar -xf libevent-2.1.8-stable.tar.gz -C /usr/local/src
#		cd /usr/local/src/libevent-2.1.8-stable
#		./configure --prefix=/usr/local/libevent
#		make -j ${cpunu} && make install

		#编译安装 memcached
		cd
		if [ ! -f memcached-1.5.2.tar.gz ]
		then
			wget http://download.hyahm.com/memcached-1.5.2.tar.gz
		fi
		tar -xf memcached-1.5.2.tar.gz -C /usr/local/src
		cd /usr/local/src/memcached-1.5.2
		./configure --prefix=/usr/local/memcached
		make -j ${cpunu} && make install

		#编译安装 Memcached 扩展插件依赖的 libmemcached 库
		cd
		if [ ! -f libmemcached-1.0.18.tar.gz  ]
		then
			wget http://download.hyahm.com/libmemcached-1.0.18.tar.gz
		fi
		tar -xf libmemcached-1.0.18.tar.gz -C /usr/local/src
		cd /usr/local/src/libmemcached-1.0.18
		sed -i 's/opt_servers == false/opt_servers == NULL/g' clients/memflush.cc
		./configure --prefix=/usr/local/libmemcached --with-memcached=/usr/local/memcached/bin/memcached
		make -j ${cpunu} && make install

		#编译安装 PHP PECL 的 Memcached 扩展
		cd
		if [ ${phpnum} -eq 7 ]
		then
			if [ ! -f memcached-3.0.3.tgz ]
			then
				wget http://download.hyahm.com/memcached-3.0.3.tgz
			fi
			tar -xf memcached-3.0.3.tgz -C /usr/local/src
			cd  /usr/local/src/memcached-3.0.3
		else
			if [ ! -f memcached-2.2.0.tgz ]
            	then
                	wget http://download.hyahm.com/memcached-2.2.0.tgz
           		tar -xf memcached-2.2.0.tgz -C /usr/local/src
           		cd  /usr/local/src/memcached-2.2.0	
           	fi
		fi
			${phppath}/bin/phpize
			./configure --with-php-config=${phppath}/bin/php-config --with-libmemcached-dir=/usr/local/libmemcached
			make -j ${cpunu} && make install
	else
		echo "存在memcached 拓展，已跳过"
	fi
	
	grep  "${php_ext_dir}/memcached.so"  ${phpconfig}/php.ini
	if  [ $? -ne 0 ]
	then
		echo "extension=${php_ext_dir}/memcached.so" >>  ${phpconfig}/php.ini
	fi
}

function startphp {

	if [ ${version} -eq 7 ]
	then
		systemctl daemon-reload
		systemctl restart php-fpm
		systemctl enable php-fpm

	else
		service php-fpm restart
		chkconfig --add php-fpm
		chkconfig php-fpm on
	fi
}

function phpyouhua {
	#php.ini的调试
	sed -i "s#;date.timezone =#date.timezone =Asia/Shanghai#" ${phpconfig}/php.ini
	sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" ${phpconfig}/php.ini
	sed -i "s#session.use_strict_mode = 0#session.use_strict_mode = 1#" ${phpconfig}/php.ini	
	sed -i "s#expose_php = On#expose_php = off#" ${phpconfig}/php.ini	
	sed -i "s#cgi.fix_pathinfo=0#cgi.fix_pathinfo=1#" ${phpconfig}/php.ini
	grep  "${php_ext_dir}/opcache.so"  ${phpconfig}/php.ini
	if  [ $? -ne 0 ]
	then
		sed -i "/\[opcache\]/a\zend_extension=${php_ext_dir}/opcache.so" ${phpconfig}/php.ini	
		sed -i "/\[opcache\]/a\;配置文件说明参考http:\/\/www.cnblogs.com\/HD\/p\/4554455.html" ${phpconfig}/php.ini
	fi	
	#开启opcache,配置文件说明参考http://www.cnblogs.com/HD/p/4554455.html
	
	sed -i "s#;opcache.enable=1#opcache.enable=1#" ${phpconfig}/php.ini
	sed -i "s#;opcache.enable_cli=0#opcache.enable_cli=1#" ${phpconfig}/php.ini
	sed -i "s#;opcache.memory_consumption=64#opcache.memory_consumption=512#" ${phpconfig}/php.ini
	sed -i "s#;opcache.max_accelerated_files=2000#;opcache.max_accelerated_files=100000#" ${phpconfig}/php.ini
	sed -i "s#;opcache.fast_shutdown=0#opcache.fast_shutdown=1#" ${phpconfig}/php.ini
	
	#配置zabbix的php.ini文件
	sed -i "s/post_max_size = 8M/post_max_size = 400M/" ${phpconfig}/php.ini
	sed -i "s/max_execution_time = 30/max_execution_time = 600/" ${phpconfig}/php.ini
	sed -i "s/max_input_time = 60/max_input_time = 600/" ${phpconfig}/php.ini
	sed -i "s#;date.timezone =#date.timezone =Asia/Shanghai#" ${phpconfig}/php.ini
	grep ";always_populate_raw_post_data = -1" ${phpconfig}/php.ini
	if [ $? -eq 0  ]
	then
		sed -i "s/;always_populate_raw_post_data = -1/always_populate_raw_post_data = -1/" ${phpconfig}/php.ini
	else
		grep "always_populate_raw_post_data = -1" ${phpconfig}/php.ini >> /dev/null
		if [ $? -ne 0  ]
		then
			echo "always_populate_raw_post_data = -1" >> ${phpconfig}/php.ini
		fi
	fi
	#sed -i "s#error_reporting = E_ALL#error_reporting = E_ALL & E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED#" ${phpconfig}php.ini
	
	#php-fpm的优化
	if [ ${phpnu} -eq 7 ]
	then
		sed -i "s/;listen.backlog = 511/listen.backlog = 1024/" ${phppath}/etc/php-fpm.d/www.conf
	fi

}

##########################   end php   #############################################


#############################     start zabbix  ##########################

function getzabbix {
	if [ ! -d  /usr/local/src/${zabbixversion} ]
	then	
		cd 
		rm -f ${zabbixversion}.tar.gz
		wget -O ${zabbixversion}.tar.gz   https://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/${zabbixdownload}/${zabbixversion}.tar.gz
		tar -xf ${zabbixversion}.tar.gz -C   /usr/local/src
	fi
}

function zabbixdepend {
	yum -y install net-snmp-devel libcurl-devel   libxml2-devel gcc  libevent-devel
	cat /etc/passwd | grep "^zabbix:"
	if [ $? -ne 0  ];then
		groupadd zabbix
		useradd -g zabbix -M -s /sbin/nologin zabbix
	fi
	
}

function zabbixserver {
	cd /usr/local/src/${zabbixversion}
	make clean
	./configure --prefix=${zabbixpath} --enable-server --enable-agent --with-mysql --enable-ipv6 --with-net-snmp --with-libcurl --with-libxml2 
	if [ $? -ne 0 ]
	then
		echo "编译错误"
		exit 1
	fi
	make install
	mysql -u root -p${mysqlpassword} -e "create database ${zabbixdb}"
	execmysql="mysql -u root -p'${mysqlpassword}'"
	if [ $? -eq 0 ]
	then

		eval ${execmysql} -e "grant all on zabbix.* to ${zabbixmysqluser}@'localhost' identified by '"${zabbixmysqlpassword}"'"
		eval ${execmysql} -e "flush privileges;"
		eval ${execmysql} ${zabbixdb} < /usr/local/src/${zabbixversion}/database/mysql/schema.sql
		eval ${execmysql} ${zabbixdb} < /usr/local/src/${zabbixversion}/database/mysql/images.sql
		eval ${execmysql} ${zabbixdb} < /usr/local/src/${zabbixversion}/database/mysql/data.sql	
	else
		eval ${execmysql} -e "drop database ${zabbixdb}"
		eval ${execmysql} -e "create database ${zabbixdb}"
		eval ${execmysql} -e "grant all on ${zabbixdb}.* to ${zabbixmysqluser}@'localhost' identified by '"${zabbixmysqlpassword}"'"
		eval ${execmysql} -e "flush privileges;"
		eval ${execmysql} ${zabbixdb} < /usr/local/src/${zabbixversion}/database/mysql/schema.sql
		eval ${execmysql} ${zabbixdb} < /usr/local/src/${zabbixversion}/database/mysql/images.sql
		eval ${execmysql} ${zabbixdb} < /usr/local/src/${zabbixversion}/database/mysql/data.sql
	fi
}

function zabbixserversetting {
	sed -i "s/DBUser=zabbix/DBUser=${zabbixmysqluser}/" ${zabbixpath}/etc/zabbix_server.conf

	sed -i "s/# DBPassword=/DBPassword=${zabbixmysqlpassword}/" ${zabbixpath}/etc/zabbix_server.conf
	sed -i "s/# DBPort=3306/DBPort=3306/" ${zabbixpath}/etc/zabbix_server.conf
	sed -i  "s/# UnsafeUserParameters=0/UnsafeUserParameters=1/"  ${zabbixpath}/etc/zabbix_agentd.conf
		
	ln -s ${zabbixpath}/sbin/* /usr/local/bin/
	cp /usr/local/src/${zabbixversion}/misc/init.d/fedora/core5/zabbix_agentd /etc/init.d/
	cp /usr/local/src/${zabbixversion}/misc/init.d/fedora/core5/zabbix_server /etc/init.d/
	
	
	sed -i "s#\/usr\/local\/sbin\/zabbix_agentd#${zabbixpath}\/sbin\/zabbix_agentd#" /etc/init.d/zabbix_agentd
	sed -i "s#\/usr\/local\/sbin\/zabbix_server#${zabbixpath}\/sbin\/zabbix_server#" /etc/init.d/zabbix_server
	service zabbix_server start
	service zabbix_agentd start
	#添加开机自启
	chkconfig --add zabbix_agentd
	chkconfig --add zabbix_server
	chkconfig  zabbix_server on
	chkconfig  zabbix_agentd on
	
	if [ ! -d ${zabbixwebpath} ]
	then	
		mkdir -p ${zabbixwebpath}
	fi
	#复制web文件到根目录
	rm -fr ${zabbixwebpath}
	mkdir -p ${zabbixwebpath}
	cp -a /usr/local/src/${zabbixversion}/frontends/php/* ${zabbixwebpath}
	#nginx的虚拟主机配置
	cat>${nginxconfigpath}/zabbix.conf<<EOF
server {
	listen ${zabbixport};
	server_name ${mynetip};
	root ${zabbixwebpath};
	charset utf-8;
	error_log logs/zabbix.error.log; 
	location / {
            index  index.php index.html index.htm;
    }
	location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
            include        fastcgi_params;
    }
}
EOF

	if [ ${version} -eq 7 ]
	then
		systemctl restart php-fpm
	else
		service php-fpm restart
	fi
	nginx -s reload
	#修改字体
	mv ${zabbixwebpath}/fonts/DejaVuSans.ttf  ${zabbixwebpath}/fonts/DejaVuSans.ttf.bak
	sed -i '/strtolower(substr/a\$val = intval($val);'  ${zabbixwebpath}/include/func.inc.php 
	cat ${zabbixwebpath}/conf/zabbix.conf.php <<EOF
<?php
// Zabbix GUI configuration file.
global \$DB;

\$DB['TYPE']     = 'MYSQL';
\$DB['SERVER']   = 'localhost';
\$DB['PORT']     = '0';
\$DB['DATABASE'] = 'zabbix';
\$DB['USER']     = '${zabbixmysqluser}';
\$DB['PASSWORD'] = '${zabbixmysqlpassword}';

// Schema name. Used for IBM DB2 and PostgreSQL.
$DB['SCHEMA'] = '';

\$ZBX_SERVER      = 'localhost';
\$ZBX_SERVER_PORT = '${zabbixport}';
\$ZBX_SERVER_NAME = 'zabbix';

$IMAGE_FORMAT_DEFAULT = IMAGE_FORMAT_PNG;	
EOF
	wget -O  ${zabbixwebpath}/fonts/DejaVuSans.ttf  http://download.hyahm.com/simhei.ttf  
}

function zabbixagent {
	cd /usr/local/src/${zabbixversion}
	./configure  --prefix=${zabbixpath} --enable-agent
	if [ $? -ne 0 ]
	then
		echo "编译错误"
		exit 1
	fi
	make install
}

function zabbixagentsetting {
	cat /etc/passwd | grep "^zabbix:"
	if [ $? -ne 0 ]
	then
		useradd -M -s /sbin/nologin zabbix	
	fi
	sed -i  "s/Server=127.0.0.1/Server=${zabbixserverip}/"  ${zabbixpath}/etc/zabbix_agentd.conf
	sed -i  "s/ServerActive=127.0.0.1/ServerActive=${zabbixserverip}/"  ${zabbixpath}/etc/zabbix_agentd.conf	
	sed -i  "s/Hostname=Zabbix server/Hostname=${zabbixagenthostname}/"  ${zabbixpath}/etc/zabbix_agentd.conf
	sed -i  "s/# Timeout=3/Timeout=5/"  ${zabbixpath}/etc/zabbix_agentd.conf
	sed -i  "s/# UnsafeUserParameters=0/UnsafeUserParameters=1/"  ${zabbixpath}/etc/zabbix_agentd.conf
	#添加启动脚本
	cp /usr/local/src/${zabbixversion}/misc/init.d/fedora/core5/zabbix_agentd /etc/init.d/
	sed -i "s#\/usr\/local\/sbin\/zabbix_agentd#${zabbixpath}\/sbin\/zabbix_agentd#" /etc/init.d/zabbix_agentd
	service zabbix_agentd start	#添加开机自启
	chkconfig --add zabbix_agentd

	chkconfig  zabbix_agentd on
	ln -s  ${zabbixpath}/sbin/zabbix_agentd /usr/bin/
	zabbix_agentd &> /dev/null
	if [ $? -ne 0 ]
	then
		echo "server/serveractive can not be null,you cat open ${zabbixpath}/etc/zabbix_agentd.conf to add"
	fi
}


##############################   end zabbix   ###########################


###############################    start vsftp   #################################
function adduser { 

#每天添加用户都需要重新生产db文件
echo "${ftpuser}" >> /etc/vsftpd/vsftp_user.txt
echo "${ftppassword}" >> /etc/vsftpd/vsftp_user.txt
if [ -f /etc/vsftpd/vsftp_user.db  ]
then
	rm -f /etc/vsftpd/vsftp_user.db
fi
db_load -T -t hash -f /etc/vsftpd/vsftp_user.txt /etc/vsftpd/vsftp_user.db

if [ ! -d ${ftpdir} ]  
then
	mkdir -p ${ftpdir}
fi

chmod 600 /etc/vsftpd/vsftp_user.db
grep  "vsftpd/vsftp_user" /etc/pam.d/vsftpd
if [ $? -ne 0 ]
then
	echo "auth   required  /lib64/security/pam_userdb.so  db=/etc/vsftpd/vsftp_user" > /etc/pam.d/vsftpd
	echo "account    required  /lib64/security/pam_userdb.so  db=/etc/vsftpd/vsftp_user" >> /etc/pam.d/vsftpd
fi

useradd -d ${ftpdir} -s /sbin/nologin  ${sysftpuser}

chmod -R 777 ${ftpdir}

cat /etc/vsftpd/vsftpd.conf | grep "anonymous_enable=YES"
if [  $? -eq 0 ]
then
	sed -i "s/anonymous_enable=YES/anonymous_enable=no/"  /etc/vsftpd/vsftpd.conf
	sed -i "s/#chroot_local_user=YES/chroot_local_user=YES/"  /etc/vsftpd/vsftpd.conf 
	sed -i "/tcp_wrappers=YES/a\allow_writeable_chroot=YES"  /etc/vsftpd/vsftpd.conf 
	sed -i "/tcp_wrappers=YES/a\user_config_dir=/etc/vsftpd/vuserconfig"  /etc/vsftpd/vsftpd.conf
	sed -i "/allow_writeable_chroot=YES/a\max_clients=10"  /etc/vsftpd/vsftpd.conf
	sed -i "/allow_writeable_chroot=YES/a\max_per_ip=5"  /etc/vsftpd/vsftpd.conf
	echo "pasv_promiscuous=YES" >>  /etc/vsftpd/vsftpd.conf
fi

if [ ${version} -ne 7 ]
then
	sed -i 's/allow_writeable_chroot=YES/#allow_writeable_chroot=YES/' /etc/vsftpd/vsftpd.conf
fi

if [ ! -d /etc/vsftpd/vuserconfig ]
then
	mkdir /etc/vsftpd/vuserconfig
fi


cat > /etc/vsftpd/vuserconfig/${ftpuser} <<EOF
#根目录
local_root=${ftpdir}
#开启虚拟帐号登录          
guest_enable=yes
#设置ftp对应的系统帐号为${sysftpuser}                    
guest_username=${sysftpuser}
# 允许匿名用户浏览器整个服务器的文件系统           
anon_world_readable_only=no
#允许在文件系统写入权限            
write_enable=yes
#允许创建文件夹                                 
anon_mkdir_write_enable=yes
# 开启匿名帐号的上传功能                 
anon_upload_enable=yes
#限定传输速度为100KB/s                     
#anon_max_rate=100000
#删除/重命名的权限                        
anon_other_write_enable=YES
EOF

}

function servicevsftp {
	if [  ${version} -eq 7 ]
	then
		systemctl restart vsftpd
	else
		service vsftpd restart 
	fi

}

###############################    end vsftp   #################################

###########################     control   ############################
function first_install_nginx() {
	nginxvar
	
	if [ "$1" == "-f" ]
	then
		nginx -s stop
		rm -fr ${nginxpath}
		rm -f /usr/local/bin/nginx
		download_nginx
       nginxdepend
       packages
       yincang
       install_nginx
       user_group
       nginxyouhua
       nginxconf       
	else
		if [ ! -f ${nginxpath}/sbin/nginx ]
	    then
	       download_nginx
	       nginxdepend
	       packages
	       yincang
	       install_nginx
	       user_group
	       nginxyouhua
	       nginxconf	       
		else
			echo "nginx in this path has installed,if you want to reinstall ,you can add more option -f to reinstall"
		fi
	fi
}		

function first_install_postgresql {
		postgresqlvar		
		if [ ! -f ${mysqlpath}/bin/psql -o ! -f ${postgresqldata} ]
		then
			addposgresqluser
			postgresqldepend
			downloadpostgresql
			installpostgresql
			postgresqlyouhua
			startpostgresql
		else
			echo "postgresql in this path has installed"
		fi
	}

function first_install_mysql() {
	mysqlvar
	if [ ! -f ${mysqlpath}/bin/mysql  ]
	then		
		mysqldepend
		getmysql
		mysqluser
		if [  ${version} -eq 7 ]
		then
			installmysql7
		else
			installmysql
		fi
		mysqlsetting $1		
		upmysql	
    else
		
		echo "mysql in this path has installed"	
	fi
}

function first_install_php() {
	phpvar
	
	phpnu=`echo ${phpversion} | awk -F - '{print $2}' | awk -F . '{print $1}'`
	if [ "$1" == "-f" ]
	then
		# 停止服务
		pkill php-fpm
		# 删除文件
		rm -fr ${phppath}/php
		rm -f ${phppath}/bin/php*
		rm -fr ${phppath}/etc/php-fpm*
		# 备份配置文件
		mv ${phpconfig}php.ini  ${phpconfig}php.ini.bak

		getphp
        phpdepend	
        	
		install_libiconv
		if [ ${phpnu} -eq 7 ]
		then
			installphp7
        	phpconfig
			phpswoole2	
		else
		    installphp
        	phpconfig
			phpswoole
		fi
		phpmemcached
        phpredis        
		phpyouhua
		phppostgresql
		phpimageick
		phpmongodb
		startphp
	else
		if [ ! -f ${phppath}/bin/php ]
	    then
			getphp
	        phpdepend	
	        		
			install_libiconv
			if [ ${phpnu} -eq 7 ]
			then
				installphp7
				phpconfig
				phpswoole2	
			else
			    installphp
			    phpconfig
				phpswoole
			fi
			phpmongodb
	        
	        phpredis 
	        phppostgresql     
			phpyouhua
			phpimageick
			phpmemcached			
			startphp
	    else
	        echo "php in this path has installed,if you want to reinstall ,you can add more option -f to reinstall" 
	    fi
	fi
}


function first_install_zabbix_server {
	zabbixvar
	mysql -u root -p${mysqlpassword} -e "show databases"	
	if [ $? -ne 0 ]
	then
		echo "can not to connect your mysql"
	else
		zabbixvar
		
		getzabbix	
		zabbixdepend
		zabbixserver
		zabbixserversetting
		
	fi
}


function first_install_zabbix_agent() {
		if [ -n "$1" ]
		then
			zabbixserverip="$1"
			zabbixvar
			getzabbix	
			zabbixdepend
			zabbixagent
			zabbixagentsetting
		else
			echo "you must input your server ip or hostname in the end"
			echo "egg:sh hyahm.sh zabbix_agent 192.168.3.5"
		fi
}

function first_install_vsftp() {
	yum -y install vsftpd
	ftpvar
	
	if [ -n "$1" ]
	then
		ftpuser="$1"
	fi

	if [ -n "$2" ]
	then
		ftppassword="$2"
	fi

	if [ -n "$3" ]
	then
		webname="$3"
	fi

	sysftpuser="virftp"${webname}
	ftpdir="${homedir}"
	if [ -f /etc/vsftpd/vuserconfig/${ftpuser}  ]
	then
        echo "this user has alived"
		exit 1
	fi
	adduser
	servicevsftp
}

###############################  start composer  ##########################

function first_install_composer {
	which php
	if [ $? -ne 0 ];then
		php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
		php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
		php composer-setup.php
		php -r "unlink('composer-setup.php');"
		mv composer.phar /bin/composer
		composer config -g repo.packagist composer https://packagist.phpcomposer.com
		echo "成功设置成中国镜像"
	else
		echo "please install php frist"
	fi
}

##############################   nocommandfuc  ##################

function help {
	echo "option must be need"
	echo "e.g :  sh hyahm.sh nginx"
    echo "nginx             	install nginx"
    echo "mysql             	install mysql"
    echo "php               	install php"
    echo "lnmp              	install nginx+mysql+php"
    echo "zabbix-server     	install zabbix-server"
    echo "zabbix-agent     		install zabbix-agent"
    echo "vsftp     			install vsftp"
	echo "tools     			install usually softs"
	echo "postgresql			install postgresql"
	echo "npm   				use aliyun registry"
	echo "composer 				install composer and use china registry"
	echo "test             		you can test function"				
}

function tools {
	cd
	yum -y install iftop  sysstat  fping sshfs smartmontools iotop
	wget https://download.samba.org/pub/linux-cifs/cifs-utils/cifs-utils-6.6.tar.bz2
	tar -xf cifs-utils-6.6.tar.bz2 -C /usr/local/src/
	./configure 
	if [ $? -ne 0 ]
	then
		echo "编译错误"
		exit 1
	fi
	make -j ${cpunu}
	make install
}

function test {
	echo ${mynetip}
}


############################  end control   ###########################

case $1 in
	'nginx')
		public
		first_install_nginx $2
	;;

	'mysql')
		public
		first_install_mysql $2
		
	;;

	'lnmp')
		public
		first_install_nginx
		first_install_mysql
		first_install_php		
	;;

	'php')
		public
		first_install_php $2
	;;
	
	'zabbix-server')
		public
		first_install_zabbix_server
	;;
	'vsftp')
		public
		first_install_vsftp $2 $3 $4
	;;
	'-h')
		help
	;;
	'tools')
		tools
	;;
	'zabbix-agent')
		public
		first_install_zabbix_agent $2
	;;
	'postgresql')
		public
		first_install_postgresql
	;;	
	'composer')
		first_install_composer
	;;
	'npm')
		npm config set registry https://registry.npm.taobao.org 
		echo "成功设置成淘宝镜像"
	;;
	'test')
		public
		phpvar
		phpmemcached
	;;
	*)
		help	
	;;
esac
