#!/bin/bash

# 颜色定义
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
RESET='\033[0m'

# 日志函数（带颜色）
log() {
    local level=$1
    local msg=$2
    case $level in
        INFO)    echo -e "${BLUE}[INFO]${RESET} $msg" ;;
        SUCCESS) echo -e "${GREEN}[SUCCESS]${RESET} $msg" ;;
        WARNING) echo -e "${YELLOW}[WARNING]${RESET} $msg" ;;
        ERROR)   echo -e "${RED}[ERROR]${RESET} $msg" ;;
    esac
}

# 检查防火墙状态
check_firewall_status() {
    local status=$(systemctl is-active firewalld)
    if [ "$status" != "active" ]; then
        log WARNING "防火墙未激活，正在启动..."
        systemctl start firewalld
        if [ $? -eq 0 ]; then
            log SUCCESS "防火墙启动成功"
        else
            log ERROR "防火墙启动失败，请手动检查"
            exit 1
        fi
    else
        log INFO "防火墙状态：已激活"
    fi
}

# 检查 80 端口是否放行
check_port_status() {
    local port_status=$(firewall-cmd --query-port=80/tcp)
    if [ "$port_status" == "yes" ]; then
        log SUCCESS "80 端口已放行（TCP协议）"
        return 0
    else
        log WARNING "80 端口未放行，正在添加规则..."
        return 1
    fi
}

# 放行 80 端口
allow_port() {
    firewall-cmd --permanent --add-port=80/tcp > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        log INFO "80 端口永久放行规则已添加"
    else
        log ERROR "添加端口规则失败"
        exit 1
    fi
    
    log INFO "重新加载防火墙规则..."
    firewall-cmd --reload > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        log SUCCESS "防火墙规则重新加载成功"
    else
        log ERROR "防火墙规则重新加载失败"
        exit 1
    fi
}

# 主流程
main() {
    log INFO "开始检查 80 端口防火墙状态..."
    
    # 检查防火墙是否运行
    check_firewall_status
    
    # 检查端口状态
    if ! check_port_status; then
        allow_port
        check_port_status  # 再次检查确认
    fi
    
    log INFO "80 端口防火墙检查及配置完成"
}

# 执行主函数
main