#!/bin/bash

# =============================================
# 判官标准版 - 一键免杀流水线
# 整合所有免杀工具，一键处理APK
# =============================================

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
CYAN='\033[0;36m'
PURPLE='\033[1;35m'
NC='\033[0m'

# 目录设置
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUTPUT_DIR="$SCRIPT_DIR/pipeline_output"
TEMP_DIR="$SCRIPT_DIR/pipeline_temp"
KEYSTORE_DIR="$SCRIPT_DIR/keystore"

mkdir -p "$OUTPUT_DIR" "$TEMP_DIR" "$KEYSTORE_DIR"

# 随机字符串生成
generate_random_string() {
    local length=$1
    cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w $length | head -n 1
}

generate_random_number() {
    local min=$1
    local max=$2
    echo $((RANDOM % (max - min + 1) + min))
}

# 清理临时文件
cleanup() {
    rm -rf "$TEMP_DIR"/* 2>/dev/null
}

# 显示进度条
show_progress() {
    local current=$1
    local total=$2
    local width=40
    local percent=$((current * 100 / total))
    local filled=$((current * width / total))
    local empty=$((width - filled))
    
    printf "\r["
    printf "%${filled}s" | tr ' ' '█'
    printf "%${empty}s" | tr ' ' '░'
    printf "] %3d%%" $percent
}

# 步骤1: 生成随机签名证书
generate_random_cert() {
    echo -e "${CYAN}[步骤1/6] 生成随机签名证书...${NC}"
    
    local alias_name="key_$(generate_random_string 8)"
    local store_pass="$(generate_random_string 12)$(generate_random_number 100 999)"
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local keystore_file="$KEYSTORE_DIR/cert_${timestamp}.jks"
    
    # 随机DN信息
    local companies=("北京科技" "上海网络" "深圳信息" "广州数据" "杭州智能")
    local cn="${companies[$RANDOM % ${#companies[@]}]}$(generate_random_string 4)有限公司"
    local ou="技术部"
    local depts=("研发中心" "产品部" "创新实验室")
    local o="${depts[$RANDOM % ${#depts[@]}]}"
    
    keytool -genkeypair \
        -alias "$alias_name" \
        -keyalg RSA \
        -keysize 2048 \
        -validity 3650 \
        -keystore "$keystore_file" \
        -storepass "$store_pass" \
        -keypass "$store_pass" \
        -dname "CN=$cn, OU=$ou, O=$o, L=Beijing, ST=Beijing, C=CN" \
        2>/dev/null
    
    if [ $? -eq 0 ]; then
        echo -e "  ${GREEN}✓${NC} 证书生成成功"
        echo "$keystore_file|$alias_name|$store_pass" > "$TEMP_DIR/cert_info.txt"
        return 0
    else
        echo -e "  ${RED}✗${NC} 证书生成失败"
        return 1
    fi
}

# 步骤2: 解包APK
unpack_apk() {
    local input_apk=$1
    echo -e "${CYAN}[步骤2/6] 解包APK文件...${NC}"
    
    if command -v apktool &> /dev/null; then
        apktool d "$input_apk" -o "$TEMP_DIR/unpacked" -f 2>/dev/null
    elif [ -f "$SCRIPT_DIR/apktool.jar" ]; then
        java -jar "$SCRIPT_DIR/apktool.jar" d "$input_apk" -o "$TEMP_DIR/unpacked" -f 2>/dev/null
    else
        echo -e "  ${RED}✗${NC} 未找到apktool"
        return 1
    fi
    
    if [ -d "$TEMP_DIR/unpacked" ]; then
        echo -e "  ${GREEN}✓${NC} 解包成功"
        return 0
    else
        echo -e "  ${RED}✗${NC} 解包失败"
        return 1
    fi
}

# 步骤3: 注入随机属性到Manifest
inject_manifest_attrs() {
    echo -e "${CYAN}[步骤3/6] 注入Manifest随机属性...${NC}"
    
    local manifest="$TEMP_DIR/unpacked/AndroidManifest.xml"
    if [ ! -f "$manifest" ]; then
        echo -e "  ${RED}✗${NC} 未找到AndroidManifest.xml"
        return 1
    fi
    
    # 注入随机meta-data
    local inject_count=$(generate_random_number 5 10)
    local meta_content=""
    
    for i in $(seq 1 $inject_count); do
        local name="com.$(generate_random_string 6).$(generate_random_string 4).config$(generate_random_string 4)"
        local value=$(generate_random_string 12)
        meta_content="$meta_content        <meta-data android:name=\"$name\" android:value=\"$value\" />\n"
    done
    
    # 插入到</application>前
    sed -i "s|</application>|$meta_content    </application>|" "$manifest"
    
    # 添加随机注释
    local comments_count=$(generate_random_number 3 6)
    for i in $(seq 1 $comments_count); do
        local comment="<!-- $(generate_random_string 32) -->"
        sed -i "1a$comment" "$manifest"
    done
    
    echo -e "  ${GREEN}✓${NC} 注入 $inject_count 个meta-data, $comments_count 个注释"
    return 0
}

# 步骤4: 增加随机文件
add_random_files() {
    echo -e "${CYAN}[步骤4/6] 添加随机数据文件...${NC}"
    
    local assets_dir="$TEMP_DIR/unpacked/assets"
    mkdir -p "$assets_dir"
    
    local file_count=$(generate_random_number 3 7)
    local total_size=0
    
    for i in $(seq 1 $file_count); do
        local size=$(generate_random_number 10 100)  # KB
        local ext=("dat" "bin" "cfg" "res" "cache")
        local filename="$(generate_random_string 8).${ext[$RANDOM % ${#ext[@]}]}"
        
        dd if=/dev/urandom of="$assets_dir/$filename" bs=1024 count=$size 2>/dev/null
        total_size=$((total_size + size))
    done
    
    echo -e "  ${GREEN}✓${NC} 添加 $file_count 个文件, 共 ${total_size}KB"
    return 0
}

# 步骤5: 重新打包
repack_apk() {
    local output_name=$1
    echo -e "${CYAN}[步骤5/6] 重新打包APK...${NC}"
    
    local unsigned_apk="$TEMP_DIR/${output_name}_unsigned.apk"
    
    if command -v apktool &> /dev/null; then
        apktool b "$TEMP_DIR/unpacked" -o "$unsigned_apk" 2>/dev/null
    elif [ -f "$SCRIPT_DIR/apktool.jar" ]; then
        java -jar "$SCRIPT_DIR/apktool.jar" b "$TEMP_DIR/unpacked" -o "$unsigned_apk" 2>/dev/null
    fi
    
    if [ -f "$unsigned_apk" ]; then
        echo -e "  ${GREEN}✓${NC} 打包成功"
        echo "$unsigned_apk" > "$TEMP_DIR/unsigned_path.txt"
        return 0
    else
        echo -e "  ${RED}✗${NC} 打包失败"
        return 1
    fi
}

# 步骤6: 签名APK
sign_apk() {
    local output_name=$1
    echo -e "${CYAN}[步骤6/6] 签名APK文件...${NC}"
    
    local unsigned_apk=$(cat "$TEMP_DIR/unsigned_path.txt")
    local cert_info=$(cat "$TEMP_DIR/cert_info.txt")
    local keystore=$(echo $cert_info | cut -d'|' -f1)
    local alias=$(echo $cert_info | cut -d'|' -f2)
    local pass=$(echo $cert_info | cut -d'|' -f3)
    
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local signed_apk="$OUTPUT_DIR/${output_name}_pipeline_${timestamp}.apk"
    
    # 使用apksigner签名
    if [ -f "$SCRIPT_DIR/apksigner.jar" ]; then
        java -jar "$SCRIPT_DIR/apksigner.jar" sign \
            --ks "$keystore" \
            --ks-pass "pass:$pass" \
            --ks-key-alias "$alias" \
            --key-pass "pass:$pass" \
            --out "$signed_apk" \
            "$unsigned_apk" 2>/dev/null
    elif command -v apksigner &> /dev/null; then
        apksigner sign \
            --ks "$keystore" \
            --ks-pass "pass:$pass" \
            --ks-key-alias "$alias" \
            --key-pass "pass:$pass" \
            --out "$signed_apk" \
            "$unsigned_apk" 2>/dev/null
    else
        # 使用jarsigner作为备选
        jarsigner -keystore "$keystore" \
            -storepass "$pass" \
            -keypass "$pass" \
            -signedjar "$signed_apk" \
            "$unsigned_apk" \
            "$alias" 2>/dev/null
    fi
    
    if [ -f "$signed_apk" ]; then
        echo -e "  ${GREEN}✓${NC} 签名成功"
        echo "$signed_apk"
        return 0
    else
        echo -e "  ${RED}✗${NC} 签名失败"
        return 1
    fi
}

# 一键处理函数
process_apk() {
    local input_apk=$1
    
    if [ ! -f "$input_apk" ]; then
        echo -e "${RED}错误: APK文件不存在: $input_apk${NC}"
        return 1
    fi
    
    local start_time=$(date +%s)
    local basename=$(basename "$input_apk" .apk)
    
    echo ""
    echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║    判官标准版 - 一键免杀流水线           ║${NC}"
    echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "输入文件: ${GREEN}$input_apk${NC}"
    echo -e "文件大小: ${GREEN}$(du -h "$input_apk" | cut -f1)${NC}"
    echo ""
    
    # 清理临时目录
    cleanup
    
    # 执行流水线
    generate_random_cert || return 1
    unpack_apk "$input_apk" || return 1
    inject_manifest_attrs || return 1
    add_random_files || return 1
    repack_apk "$basename" || return 1
    local output_file=$(sign_apk "$basename") || return 1
    
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    
    echo ""
    echo -e "${BLUE}══════════════════════════════════════════${NC}"
    echo -e "${GREEN}✓ 处理完成!${NC}"
    echo -e "  输出文件: ${CYAN}$output_file${NC}"
    echo -e "  处理用时: ${CYAN}${duration}秒${NC}"
    echo -e "${BLUE}══════════════════════════════════════════${NC}"
    
    # 清理临时文件
    cleanup
    
    return 0
}

# 批量处理
batch_process() {
    local input_dir=$1
    
    echo -e "${BLUE}批量处理目录: $input_dir${NC}"
    
    local count=0
    local success=0
    
    for apk in "$input_dir"/*.apk; do
        if [ -f "$apk" ]; then
            echo ""
            echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
            echo -e "处理 [$((count+1))]: $(basename $apk)"
            echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
            
            if process_apk "$apk"; then
                ((success++))
            fi
            ((count++))
        fi
    done
    
    echo ""
    echo -e "${GREEN}批量处理完成!${NC}"
    echo -e "  总计: ${CYAN}$count 个${NC}"
    echo -e "  成功: ${GREEN}$success 个${NC}"
    echo -e "  失败: ${RED}$((count - success)) 个${NC}"
}

# 主菜单
show_menu() {
    clear
    echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║    判官标准版 - 一键免杀流水线           ║${NC}"
    echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "  ${GREEN}1.${NC} 处理单个APK"
    echo -e "  ${GREEN}2.${NC} 批量处理APK"
    echo -e "  ${GREEN}3.${NC} 查看输出目录"
    echo -e "  ${GREEN}4.${NC} 清理临时文件"
    echo -e "  ${GREEN}0.${NC} 退出"
    echo ""
    echo -n "请选择 [0-4]: "
}

# 主函数
main() {
    # 检查Java
    if ! command -v java &> /dev/null; then
        echo -e "${RED}错误: 未安装Java，请先安装JDK${NC}"
        exit 1
    fi
    
    while true; do
        show_menu
        read -r option
        case $option in
            1)
                echo -n "请输入APK路径: "
                read -r apk_path
                process_apk "$apk_path"
                echo -n "按回车继续..."
                read
                ;;
            2)
                echo -n "请输入APK目录: "
                read -r dir_path
                batch_process "$dir_path"
                echo -n "按回车继续..."
                read
                ;;
            3)
                echo -e "${CYAN}输出目录:${NC}"
                ls -lh "$OUTPUT_DIR"/*.apk 2>/dev/null || echo "暂无文件"
                echo -n "按回车继续..."
                read
                ;;
            4)
                cleanup
                echo -e "${GREEN}临时文件已清理${NC}"
                sleep 1
                ;;
            0)
                cleanup
                echo -e "${GREEN}再见!${NC}"
                exit 0
                ;;
        esac
    done
}

main "$@"
