#!/bin/bash
sleep 15
# 配置参数
API_BASE="http://osapi.pute.cn/api"
LOGIN_API="$API_BASE/auth/login"
ADMIN_USER="admin"
ADMIN_PASS="myiis@123."  # 管理员密码
OUTPUT_FILE="/opt/pppoe/pppoe_user.txt"

# 日志函数
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 检查jq是否安装
if ! command -v jq &> /dev/null; then
  log "错误: jq工具未安装，请先安装jq"
  exit 1
fi

# 读取device_id
if [ ! -f /etc/device_id ]; then
  log "错误: /etc/device_id文件不存在"
  exit 1
fi

DEVICE_ID=$(cat /etc/device_id)
PPP_API="$API_BASE/servers/$DEVICE_ID/ppp"

# 创建输出目录
mkdir -p /opt/pppoe || {
  log "错误: 无法创建/opt/pppoe目录"
  exit 1
}

# 获取JWT token
JWT_TOKEN=$(curl -s -X POST "$LOGIN_API" \
  -H "Content-Type: application/json" \
  -d "{\"username\":\"$ADMIN_USER\",\"password\":\"$ADMIN_PASS\"}" | jq -r '.access_token')

if [ -z "$JWT_TOKEN" ] || [ "$JWT_TOKEN" = "null" ]; then
  log "错误: 获取JWT token失败"
  exit 1
fi

log "开始获取PPP配置信息..."
# 调用API获取PPP配置
response=$(curl -s -X GET "$PPP_API" \
  -H "accept: application/json" \
  -H "Authorization: Bearer $JWT_TOKEN")

# 检查是否获取到有效数据
if [ -z "$response" ]; then
  log "错误: 无法获取PPP配置信息"
  exit 1
fi

# 处理返回数据并写入文件
echo "$response" | jq -r '.[] | "\(if .vlanId == null or .vlanId == 0 or .vlanId == 1 then "novlan" else .vlanId end) \(.pppAccount) \(.pppPassword) \(.eth) \(.bandWidth)"' > "$OUTPUT_FILE" || {
  log "错误: 处理PPP配置信息失败"
  exit 1
}

log "成功: PPP配置信息已保存到 $OUTPUT_FILE"
exit 0
