
#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 统一单位计算函数（KB）
calc_usage() {
    total_kb=$(grep -E "^${1}:" /proc/meminfo | awk '{print $2}')
    used_kb=$(grep -E "^${1}:" /proc/meminfo | awk '{print $2}' | head -1)
    [ $total_kb -eq 0 ] && echo "0%" || echo "$((used_kb*100/total_kb))%"
}

# 检查root权限
[ "$(id -u)" -ne 0 ] && echo -e "${RED}错误：请使用sudo运行${NC}" && exit 1

# 处理现有交换文件
if swapon --show | grep -q "/swapfile"; then
    echo -e "${YELLOW}[1/7] 禁用并删除旧交换文件...${NC}"
    swapoff /swapfile && rm -f /swapfile || { echo -e "${RED}✗ 清理失败${NC}"; exit 1; }
    echo -e "${GREEN}✓ 清理完成${NC}"
fi

# 创建交换文件
echo -e "${YELLOW}[2/7] 创建8GB交换文件...${NC}"
dd if=/dev/zero of=/swapfile bs=1M count=8192 status=progress || exit 1

# 设置权限
chmod 600 /swapfile || exit 1

# 格式化交换空间
mkswap /swapfile || exit 1

# 启用交换空间
swapon /swapfile || exit 1

# 配置开机挂载
grep -q "/swapfile" /etc/fstab || echo "/swapfile none swap sw 0 0" >> /etc/fstab

# 显示内存状态（统一KB单位）
echo -e "${YELLOW}[7/7] 当前内存状态：${NC}"
echo "----------------------------------"
awk '/^MemTotal/{t=$2}/^MemAvailable/{a=$2}END{printf "物理内存: %.1fG/%.1fG (使用率: %d%%)\n",(t-a)/1048576,t/1048576,(t-a)*100/t}' /proc/meminfo
awk '/^SwapTotal/{t=$2}/^SwapFree/{f=$2}END{printf "交换空间: %.1fG/%.1fG (使用率: %d%%)\n",(t-f)/1048576,t/1048576,(t-f)*100/t}' /proc/meminfo
echo "----------------------------------"
swapon --show
