#!/bin/bash
basepath=$(cd `dirname $0`; pwd)
cd $basepath
MIN_LENGTH=2
MAX_LENGTH=8
 
# 生成一个介于MIN_LENGTH和MAX_LENGTH之间的随机数
LENGTH=$((RANDOM % ($MAX_LENGTH - $MIN_LENGTH + 1) + $MIN_LENGTH))
 
# 使用/dev/urandom生成长度为LENGTH的随机字符串
# 这里使用了tr命令来过滤出可打印字符
#random_string1=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c$LENGTH)
#random_string2=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c$LENGTH)

random_string1=$(mktemp -u XXXXXXXX)
random_string2=$(mktemp -u XXXXXXXX)
random_string3=$(mktemp -u XXXXXXXX)
random_string4=$(mktemp -u XXXXXXXX)
random_string5=$(mktemp -u XXXXXXXX)
random_string6=$(mktemp -u XXXXXXXX)



random_string2="1$random_string2"
random_string3="2$random_string3"
random_string4="b$random_string4"
random_string5="c$random_string5"
random_string6="m$random_string6"


#defaults write com.blizzard.worldofwarcraft DisableOSVersionCheck YES


cat <<EOF >$basepath/$random_string1
#!/bin/bash
# $(mktemp -u XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
EOF

cat <<'EOF2' >>$basepath/$random_string1

# =================== 可配置参数 ===================
MACHINE_OFFSETNUM=1      # 机器编号
PROFILE=1                # 使用哪套参数组（默认第1组）

BANBEN=3                 # 版本号
BASE_TIME="2025-07-01 00:00:00"  # 基准时间

# 参数组，每组: 总周期 子周期 总机器数
PARAMS_GROUPS=(
    "528 70 4"   # 第1套
    "264 70 2"   # 第2套
    # 可以继续添加新的参数组
)

# =================== 函数 ===================
function date_to_timestamp() {
    if [[ "$(uname)" == "Darwin" ]]; then
        date -j -f "%Y-%m-%d %H:%M:%S" "$1" +%s 2>/dev/null
    else
        date -d "$1" +%s 2>/dev/null
    fi
}

# 刷新当前参数组
function refresh_params() {
    CURRENT_PARAMS=(${PARAMS_GROUPS[$((PROFILE-1))]})
    TOTAL_CYCLE=${CURRENT_PARAMS[0]}
    SUB_CYCLE=${CURRENT_PARAMS[1]}
    MACHINE_COUNT=${CURRENT_PARAMS[2]}
    MACHINE_OFFSET=$((MACHINE_OFFSETNUM * TOTAL_CYCLE / MACHINE_COUNT))
}

# 初始刷新
refresh_params

# =================== 启动交互菜单 ===================
echo "===== 当前配置 ====="
echo "机器编号=$MACHINE_OFFSETNUM"
echo "参数集编号=$PROFILE: ${PARAMS_GROUPS[$((PROFILE-1))]}"
echo "总机器数=$MACHINE_COUNT"
echo "1) 修改 机器编号"
echo "2) 切换参数集"
echo "回车直接运行"
read -p "选择操作: " choice

if [[ "$choice" == "1" ]]; then
    read -p "请输入新的 机器编号: " newnum
    if [[ "$newnum" =~ ^[0-9]+$ ]]; then
        MACHINE_OFFSETNUM=$newnum
        sed -i '' "s/^MACHINE_OFFSETNUM=.*/MACHINE_OFFSETNUM=$newnum   # 机器编号/" "$0"
        echo "已更新 MACHINE_OFFSETNUM=$newnum"
        refresh_params
    fi
elif [[ "$choice" == "2" ]]; then
    echo "可用参数集列表："
    for i in "${!PARAMS_GROUPS[@]}"; do
        idx=$((i+1))
        echo "$idx) ${PARAMS_GROUPS[$i]}"
    done

    read -p "请输入参数集编号 (1-${#PARAMS_GROUPS[@]}): " newp
    if [[ "$newp" =~ ^[0-9]+$ ]] && (( newp >=1 && newp <= ${#PARAMS_GROUPS[@]} )); then
        PROFILE=$newp
        sed -i '' "s/^PROFILE=.*/PROFILE=$newp   # 参数集编号/" "$0"
        echo "已切换到参数集 $newp: ${PARAMS_GROUPS[$((newp-1))]}"
        refresh_params
        echo "刷新参数组: 总周期=$TOTAL_CYCLE, 子周期=$SUB_CYCLE, 总机器数=$MACHINE_COUNT"
    else
        echo "输入无效"
    fi
fi

# =================== 周期计算 ===================
current_timestamp=$(date +%s)
base_timestamp=$(date_to_timestamp "$BASE_TIME")
next_cycle_start=$((base_timestamp + ((current_timestamp - base_timestamp - MACHINE_OFFSET) / TOTAL_CYCLE + 1) * TOTAL_CYCLE + MACHINE_OFFSET))
next_cycle_human=$(date -j -f "%s" "$next_cycle_start" "+%Y-%m-%d %H:%M:%S")

echo "===== 脚本启动时间: $(date '+%Y-%m-%d %H:%M:%S') =====" > /dev/tty
echo "下一周期开始时间: $next_cycle_human 版本号: $BANBEN 总机器数: $MACHINE_COUNT 机器编号: $MACHINE_OFFSETNUM" > /dev/tty
# =================== 启动时立即判断周期 ===================
current_timestamp=$(date +%s)
elapsed_seconds=$(( (current_timestamp - base_timestamp - MACHINE_OFFSET) % TOTAL_CYCLE ))
if [ "$elapsed_seconds" -ge "$SUB_CYCLE" ]; then
    # 当前在屏蔽期
    sudo pfctl -r -ef - <<EOF1  > /dev/null 2>&1
table <temp_block> { 172.105.91.89 203.86.235.237 74.211.109.150 38.59.243.153 154.17.237.113 }
block drop from <temp_block> to any
block drop from any to <temp_block>
EOF1
    echo "[$(date +'%H:%M:%S')] 脚本启动时：当前属于屏蔽期，已开始屏蔽 机器编号: $MACHINE_OFFSETNUM" > /dev/tty
else
    # 当前在解除期
    sudo pfctl -t temp_block -T flush > /dev/null 2>&1
    echo "[$(date +'%H:%M:%S')] 脚本启动时：当前属于解除期，已解除屏蔽 版本号: $BANBEN 总机器数: $MACHINE_COUNT 机器编号: $MACHINE_OFFSETNUM" > /dev/tty
fi

# =================== 主循环 ===================
while true; do
    current_timestamp=$(date +%s)
    elapsed_seconds=$(( (current_timestamp - base_timestamp - MACHINE_OFFSET) % TOTAL_CYCLE ))

    if [ "$elapsed_seconds" -ge 0 ] && [ "$elapsed_seconds" -le 10 ]; then
        sudo pfctl -t temp_block -T flush > /dev/null 2>&1
        echo "[$(date +'%H:%M:%S')] 解除屏蔽 版本号: $BANBEN 总机器数: $MACHINE_COUNT 机器编号: $MACHINE_OFFSETNUM" > /dev/tty
        sleep $((SUB_CYCLE - elapsed_seconds -1))
    elif [ $elapsed_seconds -ge $((SUB_CYCLE + 0)) ] && [ $elapsed_seconds -le $((SUB_CYCLE + 10)) ]; then
sudo pfctl -r -ef - <<EOF1  > /dev/null 2>&1	
table <temp_block> { 172.105.91.89 203.86.235.237 74.211.109.150 38.59.243.153 154.17.237.113 }
block drop from <temp_block> to any
block drop from any to <temp_block>
EOF1
        next_cycle_start=$((base_timestamp + ((current_timestamp - base_timestamp - MACHINE_OFFSET) / TOTAL_CYCLE + 1) * TOTAL_CYCLE + MACHINE_OFFSET))
        next_cycle_human=$(date -j -f "%s" "$next_cycle_start" "+%Y-%m-%d %H:%M:%S")
        echo "[$(date +'%H:%M:%S')] 开始屏蔽 机器编号: $MACHINE_OFFSETNUM 下一次解锁时间: $next_cycle_human" > /dev/tty
        sleep $((TOTAL_CYCLE - elapsed_seconds - 2))
    fi

    sleep 1
done


EOF2


cat <<EOF >>$basepath/$random_string1
# $(mktemp -u XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
EOF
sudo chmod 777  $basepath/$random_string1

sleep 0.5

cat <<EOF >$basepath/$random_string2
#!/bin/bash
# $(mktemp -u XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
EOF
cat <<'EOF2' >>$basepath/$random_string2
sudo pfctl -r -ef - <<EOF1
table <temp_block> { 172.105.91.89 203.86.235.237 74.211.109.150 38.59.243.153 154.17.237.113 }
block drop from <temp_block> to any
block drop from any to <temp_block>
EOF1
EOF2
cat <<EOF >>$basepath/$random_string2
# $(mktemp -u XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
EOF
sudo chmod +x  $basepath/$random_string2

sleep 0.5

cat <<EOF >$basepath/$random_string3
#!/bin/bash
# $(mktemp -u XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
sudo pfctl -t temp_block -T flush
sudo renice -n -20 $(ps -ef | grep -i '[s]creensharingd' | awk '{print $2}')
# $(mktemp -u XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
EOF

sudo chmod +x $basepath/$random_string3

sleep 0.5

cat <<EOF >$basepath/$random_string5
#!/bin/bash
# $(mktemp -u XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
sudo rm -rf /Library/Logs/DiagnosticReports/Battle.net*
sudo rm -rf /Library/Preferences/net.battle.plist
sudo rm -rf /Users/Shared/Battle.net
sudo rm -rf ~/Library/Application\ Support/Battle.net
sudo rm -rf ~/Library/Application\ Support/Blizzard
sudo rm -rf ~/Library/Preferences/net.battle*
sudo rm -rf ~/Library/Preferences/com.blizzard*
sudo rm -rf ~/Library/Saved\ Application\ State/net.battle*
sudo rm -rf ~/Library/Saved\ Application\ State/com.blizzard.worldofwarcraft.savedState
sudo rm -rf ~/Library/Saved\ Application\ State/com.blizzard*
sudo rm -rf /Library/Logs/DiagnosticReports/Agent*
sudo rm -rf /Library/Logs/DiagnosticReports/WowVoiceProxy*
sudo rm -rf /Library/Logs/DiagnosticReports/World\ of\ Warcraft*
sudo rm -rf /Library/Logs/DiagnosticReports/ToDesk_Service*
sudo rm -rf ~/Library/Preferences/com.blizzard.worldofwarcraft.plist
sudo rm -rf ~/Library/Preferences/com.blizzard*
sudo rm -rf /Users/Shared/Blizzard/
sudo rm -rf ~/Library/Application\ Support/Blizzard
sudo rm -rf ~/Library/Saved\ Application\ State/com.blizzard*
sudo rm -rf ~/Library/Application\ Support/CrashReporter/World\ of\ Warcraft*
sudo rm -rf /Applications/Battle.net.app
sudo rm -rf ~/Library/Application\ Support/Battle*
sudo rm -rf ~/Library/Preferences/net.battle*

sudo rm -rf /Library/Logs/DiagnosticReports/WowVoiceProxy*
sudo rm -rf ~/Library/Application\ Support/CrashReporter/World\ of\ Warcraft*
# $(mktemp -u XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)
EOF
sudo chmod +x $basepath/$random_string5

sleep 0.5
# 正则表达式匹配：确保行格式为 "mac ALL=(ALL) NOPASSWD: /sbin/pfctl"（忽略空格数）
if ! sudo grep -Eq "^%admin[[:space:]]+ALL=\(ALL\)[[:space:]]+NOPASSWD:[[:space:]]+/sbin/pfctl" /etc/sudoers; then
    # 写入免密码配置（用户名为 mac，命令为 pfctl）
    echo "%admin ALL=(ALL) NOPASSWD: /sbin/pfctl" | sudo tee -a /etc/sudoers > /dev/null
    echo "sudoers 配置已更新，用户 mac 执行 pfctl 无需密码。"
else
    echo "sudoers 中已存在 mac 对 pfctl 的免密码配置，无需更新。"
fi
