#!/bin/bash
# M-Team 批量搜索下载脚本 - OVH KS2 迁移用
# 搜索动画种子并添加到 OVH qBittorrent

JWT="eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ4bWcwODI4OCIsInVpZCI6MzgxNDg3LCJqdGkiOiIwMTljOGNkMy01YTlhLTcyODctODQ0OS04ZTYwZjkxZWIyOTEiLCJpc3MiOiJodHRwczovL2FwaS5tLXRlYW0uaW8iLCJpYXQiOjE3NzE4ODkxODcsImV4cCI6MTc3NDQ4MTE4N30.5Xn_bYGXP8biz6yEEYP05wSaoyPI0zBX9a6YmUctyhvUYGlf58m60ta-OzOtz_GHj13xuoNVxyZXAQLmqIaatA"
SECRET="HLkPcWmycL57mfJt"
API="https://api.m-team.io"
QB_HOST="http://145.239.143.92:8080"
QB_USER="admin"
QB_PASS="Mango2026!"

# 登录 qB
login_qb() {
    SID=$(curl -s -c - "$QB_HOST/api/v2/auth/login" -d "username=$QB_USER&password=$QB_PASS" | grep SID | awk '{print $NF}')
    echo "$SID"
}

# M-Team API 搜索
search_mt() {
    local keyword="$1"
    local mode="${2:-normal}"  # normal or adult
    curl -s "$API/api/torrent/search" \
        -H "authorization: $JWT" \
        -H "Content-Type: application/json" \
        -d "{\"keyword\":\"$keyword\",\"mode\":\"$mode\",\"pageNumber\":1,\"pageSize\":30}"
}

# 生成下载 token
gen_dl_token() {
    local torrent_id="$1"
    local ts_ms=$(date +%s%3N)
    local ts_s=$((ts_ms / 1000))
    local sign_str="POST&/api/torrent/genDlToken&${ts_ms}"
    local sign=$(echo -n "$sign_str" | openssl dgst -sha1 -hmac "$SECRET" -binary | base64)
    
    curl -s "$API/api/torrent/genDlToken" \
        -H "authorization: $JWT" \
        -H "ts: $ts_s" \
        -H "visitorId: ff841bb2fb467c6f2261348af1672d67" \
        -H "version: 1.1.4" \
        -H "webVersion: 1140" \
        -H "did: a8b989661e274ff89aae7bdd2b67663e" \
        -F "id=$torrent_id" \
        -F "_timestamp=$ts_ms" \
        -F "_sgin=$sign"
}

# 添加种子到 qB
add_to_qb() {
    local dl_url="$1"
    local sid="$2"
    local savepath="${3:-/downloads}"
    curl -s -b "SID=$sid" "$QB_HOST/api/v2/torrents/add" \
        --data-urlencode "urls=$dl_url" \
        -d "savepath=$savepath"
}

echo "=== M-Team 批量下载 ==="
echo "目标: OVH KS2 (145.239.143.92)"
echo ""

# 登录 qB
echo "[1] 登录 qBittorrent..."
SID=$(login_qb)
echo "SID: $SID"

if [ -z "$SID" ]; then
    echo "ERROR: qB 登录失败"
    exit 1
fi

echo "[2] 开始搜索种子..."
echo ""
