#!/bin/bash
# WiFi AP 统一控制脚本 - 健壮版本
# 用法: wifi_ap.sh {start|stop|status|toggle|restart}

set -e

# 配置
WLAN="wlan0"
ETH="end2"
WLAN_IP="192.168.12.1"
DHCP_FILE="/etc/myir-udhcpd.conf"
HOSTAPD_FILE="/etc/myir-hostapd.conf"
PID_FILE="/var/run/wifi_ap.pid"
LOG_FILE="/var/log/aethex_gpio_wifi_ap.log"
LOCK_FILE="/tmp/wifi_ap.lock"

# 日志函数
log() {
    local level=$1
    shift
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*" | tee -a "$LOG_FILE"
}

# 错误处理
error_exit() {
    log "ERROR" "$1"
    rm -f "$LOCK_FILE"
    exit 1
}

# 获取进程锁
acquire_lock() {
    if [ -f "$LOCK_FILE" ]; then
        local pid=$(cat "$LOCK_FILE" 2>/dev/null)
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            # 检查是否是自己
            if [ "$pid" = "$$" ]; then
                return 0
            fi
            # 等待一段时间
            local count=0
            while [ $count -lt 5 ]; do
                if ! kill -0 "$pid" 2>/dev/null; then
                    break
                fi
                sleep 1
                count=$((count + 1))
            done
            # 如果还在运行，强制清理
            if kill -0 "$pid" 2>/dev/null; then
                log "WARN" "清理旧锁文件 (PID: $pid)"
                rm -f "$LOCK_FILE"
            fi
        fi
        rm -f "$LOCK_FILE"
    fi
    echo $$ > "$LOCK_FILE"
}

# 释放进程锁
release_lock() {
    rm -f "$LOCK_FILE"
}

# 清理环境
clean_stage() {
    log "INFO" "清理 WiFi 环境..."
    
    # 停止所有相关进程
    killall udhcpc 2>/dev/null || true
    killall wpa_supplicant 2>/dev/null || true
    killall hostapd 2>/dev/null || true
    killall udhcpd 2>/dev/null || true
    
    sleep 1
    
    # 清理 iptables 规则
    iptables -t nat -D POSTROUTING -s ${WLAN_IP}/24 -o ${ETH} -j MASQUERADE 2>/dev/null || true
    
    # 关闭接口
    ifconfig ${WLAN} down 2>/dev/null || true
    
    log "INFO" "清理完成"
}

# 启用 WiFi 硬件
enable_wifi() {
    log "INFO" "启用 WiFi 硬件..."

    local RFKILL_SYS_PATH="/sys/class/rfkill/"

    if [ ! -d "$RFKILL_SYS_PATH" ]; then
        log "WARN" "rfkill 路径不存在"
        return 1
    fi

    # 查找 phy* 设备（WiFi 硬件）
    for i in $(ls ${RFKILL_SYS_PATH}); do
        if [ -f "${RFKILL_SYS_PATH}${i}/name" ]; then
            local name=$(cat ${RFKILL_SYS_PATH}${i}/name)
            if [[ "${name}" == phy* ]]; then
                echo 0 > ${RFKILL_SYS_PATH}${i}/state
                log "DEBUG" "复位 ${name}"
                sleep 1
                echo 1 > ${RFKILL_SYS_PATH}${i}/state
                log "INFO" "启用 ${name}"
                return 0
            fi
        fi
    done

    log "WARN" "未找到 WiFi PHY 设备"
    return 1
}

# 检查接口是否存在
check_interface() {
    if [ ! -d "/sys/class/net/${WLAN}" ]; then
        error_exit "无线接口 ${WLAN} 不存在"
    fi
    
    if [ ! -d "/sys/class/net/${ETH}" ]; then
        log "WARN" "以太网接口 ${ETH} 不存在, NAT 功能可能不可用"
    fi
}

# 从 /etc/environment 同步 WiFi 配置到 hostapd
sync_wifi_config() {
    local env_file="/etc/environment"

    if [[ ! -f "$env_file" ]] || [[ ! -f "$HOSTAPD_FILE" ]]; then
        return 0
    fi

    # 同步 SSID (从 DevSN)
    local dev_sn
    dev_sn=$(grep "^DevSN=" "$env_file" 2>/dev/null | cut -d'=' -f2 | tr -d '"' | head -1)
    if [[ -n "$dev_sn" ]]; then
        local new_ssid="AethEx-${dev_sn}"
        local current_ssid
        current_ssid=$(grep "^ssid=" "$HOSTAPD_FILE" 2>/dev/null | cut -d'=' -f2 | head -1)
        if [[ "$current_ssid" != "$new_ssid" ]]; then
            sed -i "s|^ssid=.*|ssid=${new_ssid}|" "$HOSTAPD_FILE"
            log "INFO" "同步 SSID: ${current_ssid} -> ${new_ssid}"
        fi
    fi

    # 同步密码 (从 WLANPasswd)
    local wlan_passwd
    wlan_passwd=$(grep "^WLANPasswd=" "$env_file" 2>/dev/null | cut -d'=' -f2 | tr -d '"' | head -1)
    if [[ -n "$wlan_passwd" ]]; then
        local current_passwd
        current_passwd=$(grep "^wpa_passphrase=" "$HOSTAPD_FILE" 2>/dev/null | cut -d'=' -f2 | head -1)
        if [[ "$current_passwd" != "$wlan_passwd" ]]; then
            sed -i "s|^wpa_passphrase=.*|wpa_passphrase=${wlan_passwd}|" "$HOSTAPD_FILE"
            log "INFO" "同步 WiFi 密码"
        fi
    fi
}

# 启动 AP
start_ap() {
    acquire_lock
    
    if [ -f "$PID_FILE" ]; then
        local pid=$(cat "$PID_FILE" 2>/dev/null)
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            log "WARN" "WiFi AP 已在运行 (PID: $pid)"
            release_lock
            return 0
        fi
        rm -f "$PID_FILE"
    fi
    
    log "INFO" "========== 启动 WiFi AP =========="
    
    # 检查接口
    check_interface
    
    # 同步 WiFi 配置（SSID/密码）
    sync_wifi_config
    
    # 清理环境
    clean_stage
    
    # 启用 WiFi 硬件
    enable_wifi || log "WARN" "WiFi 硬件启用可能失败"
    
    # 配置无线接口
    ifconfig ${WLAN} up ${WLAN_IP}
    if [ $? -ne 0 ]; then
        error_exit "无法配置无线接口 ${WLAN}"
    fi
    log "INFO" "设置 WLAN IP: ${WLAN_IP}"
    
    # 配置 NAT 转发
    echo "1" > /proc/sys/net/ipv4/ip_forward
    iptables -t nat -A POSTROUTING -s ${WLAN_IP}/24 -o ${ETH} -j MASQUERADE
    log "INFO" "配置 NAT 转发"
    
    sleep 1
    
    # 检查配置文件
    if [ ! -f "$DHCP_FILE" ]; then
        error_exit "DHCP 配置文件不存在: $DHCP_FILE"
    fi
    if [ ! -f "$HOSTAPD_FILE" ]; then
        error_exit "HostAPD 配置文件不存在: $HOSTAPD_FILE"
    fi
    
    # 启动 DHCP 服务器
    udhcpd ${DHCP_FILE}
    if [ $? -ne 0 ]; then
        error_exit "启动 DHCP 服务器失败"
    fi
    log "INFO" "启动 DHCP 服务器"
    
    # 启动 HostAPD
    hostapd -B ${HOSTAPD_FILE}
    if [ $? -ne 0 ]; then
        error_exit "启动 HostAPD 失败"
    fi
    log "INFO" "启动 HostAPD"
    
    # 写入 PID 文件
    echo $$ > "$PID_FILE"
    
    log "INFO" "WiFi AP 启动成功"
    log "INFO" "SSID: $(grep '^ssid=' ${HOSTAPD_FILE} | cut -d= -f2)"
    log "INFO" "IP 地址: ${WLAN_IP}"
    
    release_lock
    return 0
}

# 停止 AP
stop_ap() {
    acquire_lock
    
    if [ ! -f "$PID_FILE" ]; then
        log "WARN" "WiFi AP 未运行"
        release_lock
        return 0
    fi
    
    log "INFO" "========== 停止 WiFi AP =========="
    
    # 停止服务
    killall hostapd 2>/dev/null || true
    killall udhcpd 2>/dev/null || true
    
    # 关闭接口
    ifconfig ${WLAN} down 2>/dev/null || true
    
    # 清理 iptables 规则
    iptables -t nat -D POSTROUTING -s ${WLAN_IP}/24 -o ${ETH} -j MASQUERADE 2>/dev/null || true
    
    # 清理文件
    rm -f "$PID_FILE"
    
    log "INFO" "WiFi AP 已停止"
    
    release_lock
    return 0
}

# 查看状态
status_ap() {
    if [ -f "$PID_FILE" ]; then
        local pid=$(cat "$PID_FILE" 2>/dev/null)
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            echo "running"
            echo "PID: $pid"
            echo "接口: ${WLAN}"
            echo "IP 地址: ${WLAN_IP}"
            
            # 显示连接的客户端
            if command -v iw &> /dev/null; then
                local clients=$(iw dev ${WLAN} station dump 2>/dev/null | grep Station | wc -l)
                echo "连接客户端数: $clients"
            fi
            
            return 0
        fi
    fi
    
    echo "stopped"
    return 1
}

# 重启 AP
restart_ap() {
    log "INFO" "重启 WiFi AP..."
    stop_ap
    sleep 2
    start_ap
}

# 切换 AP 状态
toggle_ap() {
    if status_ap > /dev/null; then
        stop_ap
    else
        start_ap
    fi
}

# 主程序
case "${1:-status}" in
    start)
        start_ap
        ;;
    stop)
        stop_ap
        ;;
    status)
        status_ap
        ;;
    toggle)
        toggle_ap
        ;;
    restart)
        restart_ap
        ;;
    *)
        echo "用法: $0 {start|stop|status|toggle|restart}"
        echo ""
        echo "命令:"
        echo "  start   - 启动 WiFi AP"
        echo "  stop    - 停止 WiFi AP"
        echo "  status  - 查看 WiFi AP 状态"
        echo "  toggle  - 切换 WiFi AP 状态"
        echo "  restart - 重启 WiFi AP"
        exit 1
        ;;
esac
