#!/bin/bash
# 自动构建脚本 - 自动增加版本号并编译APK

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${BLUE}==================================${NC}"
echo -e "${BLUE}  PDA 打印机测试应用 - 自动构建${NC}"
echo -e "${BLUE}==================================${NC}"

# 读取当前版本
BUILD_FILE="app/build.gradle.kts"
CURRENT_VERSION=$(grep "versionCode = " "$BUILD_FILE" | sed 's/.*versionCode = //' | sed 's/[^0-9]//g')
CURRENT_VERSION_NAME=$(grep "versionName = " "$BUILD_FILE" | sed 's/.*versionName = "//' | sed 's/".*//')

echo -e "${GREEN}当前版本: v${CURRENT_VERSION_NAME} (Build ${CURRENT_VERSION})${NC}"

# 计算新版本
NEW_VERSION=$((CURRENT_VERSION + 1))
# 计算新版本名称 (简单递增小版本号)
IFS='.' read -r major minor <<< "$CURRENT_VERSION_NAME"
NEW_MINOR=$((minor + 1))
NEW_VERSION_NAME="${major}.${NEW_MINOR}"

echo -e "${GREEN}新版本: v${NEW_VERSION_NAME} (Build ${NEW_VERSION})${NC}"

# 更新版本号
sed -i.bak "s/versionCode = $CURRENT_VERSION/versionCode = $NEW_VERSION/" "$BUILD_FILE"
sed -i.bak "s/versionName = \"$CURRENT_VERSION_NAME\"/versionName = \"$NEW_VERSION_NAME\"/" "$BUILD_FILE"
rm -f "${BUILD_FILE}.bak"

echo -e "${GREEN}✓ 版本号已更新${NC}"

# 清理并编译
echo -e "${BLUE}开始编译...${NC}"
./gradlew clean assembleRelease --no-daemon

if [ $? -eq 0 ]; then
    echo -e "${GREEN}==================================${NC}"
    echo -e "${GREEN}  ✓ 编译成功！${NC}"
    echo -e "${GREEN}==================================${NC}"

    # 查找生成的APK
    APK_PATH=$(find app/build/outputs/apk/release -name "*.apk" -type f | head -n 1)

    if [ -n "$APK_PATH" ]; then
        APK_SIZE=$(du -h "$APK_PATH" | cut -f1)
        echo -e "${GREEN}APK 文件: ${APK_PATH}${NC}"
        echo -e "${GREEN}文件大小: ${APK_SIZE}${NC}"

        # 可选：复制到项目根目录
        cp "$APK_PATH" "./PDA_Printer_Test_latest.apk"
        echo -e "${GREEN}✓ 已复制到: ./PDA_Printer_Test_latest.apk${NC}"
    fi
else
    echo -e "${RED}✗ 编译失败${NC}"
    # 恢复版本号
    sed -i.bak "s/versionCode = $NEW_VERSION/versionCode = $CURRENT_VERSION/" "$BUILD_FILE"
    sed -i.bak "s/versionName = \"$NEW_VERSION_NAME\"/versionName = \"$CURRENT_VERSION_NAME\"/" "$BUILD_FILE"
    rm -f "${BUILD_FILE}.bak"
    echo -e "${RED}已恢复原版本号${NC}"
    exit 1
fi
