#!/bin/bash
# Eric · 凉城
# Nginx & PHP 一键安装脚本 241205

# 确保脚本以 root 用户运行
if [ "$(id -u)" -ne 0 ]; then
  echo "此脚本需要以 root 用户运行。"
  exit 1
fi

# 设置 Nginx 版本和安装目录
NGINX_VERSION="1.27.3"
NGINX_TAR_FILE="/usr/local/nginx-${NGINX_VERSION}.tar.gz"
NGINX_DIR="/usr/local/nginx"
NGINX_SRC_DIR="/usr/local/nginx-${NGINX_VERSION}"
PHP_FLAG=0

# 更新系统并安装依赖包
echo "安装依赖包..."
apt update && apt install -y wget build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev libgd-dev

# 询问是否需要安装 PHP
read -p "是否需要安装 PHP (y/n)? " INSTALL_PHP

if [[ "$INSTALL_PHP" == "y" || "$INSTALL_PHP" == "Y" ]]; then
    echo "开始安装 PHP、PHP-FPM 和 PHP-MySQL..."
    apt install -y php php-fpm php-mysql

    PHP_FLAG=1

    # 配置 PHP服务 开机自启
    echo "配置 PHP服务 开机自启..."
    touch /etc/rc.local
    echo "service php$(php -r 'echo substr(PHP_VERSION, 0, 3);')-fpm start" >> /etc/rc.local
    chmod +x /etc/rc.local
fi

# 检查 Nginx 文件是否已经下载
if [ ! -f "$NGINX_TAR_FILE" ]; then
    echo "Nginx 文件不存在，开始下载 Nginx ${NGINX_VERSION}..."
    cd /usr/local
    wget https://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz
else
    echo "Nginx 文件已存在，跳过下载..."
fi

# 解压 Nginx
if [ ! -d "$NGINX_SRC_DIR" ]; then
    echo "解压 Nginx..."
    tar xzvf nginx-${NGINX_VERSION}.tar.gz
else
    echo "Nginx 源代码已解压，跳过解压步骤..."
fi

# 初始化 Nginx 配置
echo "初始化 Nginx 配置..."
cd "$NGINX_SRC_DIR"
./configure \
    --prefix=$NGINX_DIR \
    --sbin-path=$NGINX_DIR/sbin/nginx \
    --conf-path=$NGINX_DIR/conf/nginx.conf \
    --pid-path=/var/run/nginx.pid \
    --lock-path=/var/lock/nginx.lock \
    --error-log-path=/var/log/nginx/error.log \
    --http-log-path=/var/log/nginx/access.log \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_gzip_static_module \
    --with-http_stub_status_module \
    --with-http_realip_module \
    --with-http_addition_module \
    --with-http_sub_module \
    --with-http_dav_module \
    --with-http_flv_module \
    --with-http_mp4_module \
    --with-http_secure_link_module \
    --with-http_slice_module \
    --with-http_auth_request_module \
    --with-threads \
    --with-stream \
    --with-stream_ssl_module \
    --with-stream_realip_module \
    --with-stream_ssl_preread_module \
    --with-file-aio \
    --with-http_image_filter_module=dynamic

# 检查配置是否成功
if [ $? -ne 0 ]; then
    echo "Nginx 配置失败，请检查错误日志！"
    exit 1
fi

# 编译并安装 Nginx
echo "开始编译 Nginx..."
make -j$(nproc)
if [ $? -ne 0 ]; then
    echo "Nginx 编译失败，请检查错误日志！"
    exit 1
fi

echo "安装 Nginx..."
make install
if [ $? -ne 0 ]; then
    echo "Nginx 安装失败，请检查错误信息！"
    exit 1
fi

# 调整 nginx.conf 使 Nginx 能够正常启动
echo "调整 nginx.conf..."
sed -i '2c\user root;' /usr/local/nginx/conf/nginx.conf

# 创建 sites-available 和 sites-enabled 目录
echo "创建 sites-available 和 sites-enabled 目录..."
mkdir -p $NGINX_DIR/conf/sites-available
mkdir -p $NGINX_DIR/conf/sites-enabled

# 修改 nginx.conf 来支持 sites-enabled
echo "修改 nginx.conf 配置..."
if ! grep -q "include /usr/local/nginx/conf/sites-enabled/*;" /usr/local/nginx/conf/nginx.conf; then
    sed -i '/http {/a\    include /usr/local/nginx/conf/sites-enabled/*;' /usr/local/nginx/conf/nginx.conf
fi

# 启动 Nginx
echo "启动 Nginx..."
$NGINX_DIR/sbin/nginx

# 设置环境变量，使得 nginx 命令可以直接执行
echo "export PATH=\$PATH:/usr/local/nginx/sbin" >> ~/.bashrc

# 提示用户手动执行 source ~/.bashrc 使环境变量生效
echo "环境变量已配置。"

# 检查 Nginx 是否成功启动
if pgrep -x "nginx" > /dev/null; then
    echo "Nginx 启动成功！"
else
    echo "Nginx 启动失败，请检查日志！"
    exit 1
fi

# 创建 Nginx 服务脚本
echo "创建 Nginx 服务脚本..."

cat << 'EOF' > /etc/init.d/nginx
#!/bin/bash
#
# nginx   This shell script takes care of starting and stopping nginx.
#
# chkconfig: - 85 15
# description: Nginx is a high-performance web server and reverse proxy.
### BEGIN INIT INFO
# Provides: nginx
# Required-Start: $network $local_fs
# Required-Stop: $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop nginx
# Description: Nginx is a high-performance web server and reverse proxy.
### END INIT INFO

# Nginx binary and config paths
NGINX_BIN="/usr/local/nginx/sbin/nginx"
NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
PID_FILE="/var/run/nginx.pid"

# Function to start nginx
start() {
    echo "Starting Nginx..."
    $NGINX_BIN -c $NGINX_CONF
    if [ $? -eq 0 ]; then
        echo "Nginx started successfully!"
    else
        echo "Failed to start Nginx."
    fi
}

# Function to stop nginx
stop() {
    echo "Stopping Nginx..."
    $NGINX_BIN -s stop
    if [ $? -eq 0 ]; then
        echo "Nginx stopped successfully!"
    else
        echo "Failed to stop Nginx."
    fi
}

# Function to restart nginx
restart() {
    echo "Restarting Nginx..."
    stop
    start
}

# Function to reload nginx (for configuration reload)
reload() {
    echo "Reloading Nginx configuration..."
    $NGINX_BIN -s reload
    if [ $? -eq 0 ]; then
        echo "Nginx reloaded successfully!"
    else
        echo "Failed to reload Nginx."
    fi
}

# Check if nginx is running
status() {
    if [ -f $PID_FILE ]; then
        echo "Nginx is running with PID: $(cat $PID_FILE)"
    else
        echo "Nginx is not running."
    fi
}

# Parse the command line arguments
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    reload)
        reload
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|status}"
        exit 1
        ;;
esac

exit 0
EOF

# 赋予脚本执行权限
chmod +x /etc/init.d/nginx

# 将 Nginx 服务添加到系统启动项
update-rc.d nginx defaults

# 配置 Nginx 开机自启
echo "配置 Nginx 开机自启..."
touch /etc/rc.local
echo 'service nginx start' >> /etc/rc.local
chmod +x /etc/rc.local

# 清理下载的文件
echo "清理下载的文件和源代码目录..."

# 检查文件是否存在，若存在则删除
[ -f /usr/local/nginx-${NGINX_VERSION}.tar.gz ] && rm -f /usr/local/nginx-${NGINX_VERSION}.tar.gz

# 检查目录是否存在，若存在则删除
[ -d /usr/local/nginx-${NGINX_VERSION} ] && rm -rf /usr/local/nginx-${NGINX_VERSION}

cd ~

echo "=================================================================="

# 提示 PHP Unix 套接字和 php-fpm 配置文件位置
if [ "$PHP_FLAG" -eq 1 ]; then
    echo "PHP $(php -v | head -n 1) 已安装并启动! 您可以使用 'service php$(php -r 'echo substr(PHP_VERSION, 0, 3);')-fpm start|stop|restart|reload|status' 来管理 PHP 服务。"
    # 获取 PHP 配置文件路径
    PHP_INI_PATH=$(php --ini | grep "Loaded Configuration File" | awk -F': ' '{print $2}')
    echo "PHP 配置文件：$PHP_FPM_INI_PATH"
    echo "PHP-FPM 配置文件：/etc/php/$(php -r 'echo substr(PHP_VERSION, 0, 3);')/fpm/pool.d/www.conf"
    echo "PHP Unix 套接字：/run/php/php$(php -r 'echo substr(PHP_VERSION, 0, 3);')-fpm.sock"
    service php$(php -r 'echo substr(PHP_VERSION, 0, 3);')-fpm start
fi
echo "Nginx $(/usr/local/nginx/sbin/nginx -v 2>&1 | awk -F/ '{print $2}') 安装完成并启动! 若希望立即使用 nginx 命令，请执行 'source ~/.bashrc'。"
echo "Nginx 服务脚本已创建，您可以使用 'service nginx start|stop|restart|reload|status' 来管理 Nginx 服务。"
echo "=================================================================="
