#!/bin/bash
set -e

# 定义变量
NGINX_CONF_DIR="/etc/nginx/sites-available"  # Nginx 可用配置目录
NGINX_ENABLED_DIR="/etc/nginx/sites-enabled" # Nginx 启用配置目录
CONF_FILE="2.cemcoe.com"                     # 配置文件名
CONF_PATH="$NGINX_CONF_DIR/$CONF_FILE"       # 配置文件完整路径
LINK_PATH="$NGINX_ENABLED_DIR/$CONF_FILE"    # 符号链接完整路径

# 创建 Nginx 配置文件
echo "Configuring Nginx for 2.cemcoe.com..."
sudo tee "$CONF_PATH" <<EOL
server {
    listen 80;
    server_name 2.cemcoe.com;

    # 设置根目录
    root /var/www/2.cemcoe.com;

    # 设置默认文件
    index index.html;

    # 处理所有请求
    location / {
        try_files \$uri \$uri/ /index.html;
    }

    # 处理静态资源
    location /static/ {
        try_files \$uri =404;
    }
}
EOL

# 创建符号链接以启用配置
echo "Linking configuration to $NGINX_ENABLED_DIR..."
sudo ln -sfv "$CONF_PATH" "$LINK_PATH"

# 测试 Nginx 配置语法
echo "Testing Nginx configuration..."
if ! sudo nginx -t; then
    echo "Nginx configuration test failed. Please check the configuration file." >&2
    exit 1
fi

# 重启 Nginx 服务
echo "Restarting Nginx to apply changes..."
if sudo systemctl restart nginx; then
    echo "Nginx restarted successfully."
    sudo systemctl status nginx --no-pager
else
    echo "Failed to restart Nginx. Please check the service status." >&2
    exit 1
fi

echo "Nginx has been configured successfully for 2.cemcoe.com."