#!/usr/bin/env bash
# @author juntao
# @2023.03.06

git fetch --tags -f
git_sha=$(git rev-parse --short HEAD)
currentTag=$(git describe --tags --exact-match "$git_sha")
echo "获取当前tag结果：$currentTag"
if [[ $currentTag == *"-test"* ]]; then
    # 如果获取到tag是有-test后缀的，打的是测试包
    buildType="debug"
else
    buildType="release"
fi

versionName=$(awk -v FS="versionName = " 'NF>1{print $2}' dependencies.gradle | sed "s/\"//g")
versionCode=$(awk -v FS="versionCode = " 'NF>1{print $2}' dependencies.gradle | sed "s/\"//g")
build_time=$(TZ=Asia/Shanghai date +'%Y-%m%d-%H%M')
PACKAGE_NAME=$(sed -n "$(sed -n "/^[[:blank:]]*applicationId[[:blank:]]*=/=" dependencies.gradle)p" dependencies.gradle | awk -F '=' '{print $NF}' | sed "s/[[:blank:]]*[\"']*//g")
MODULE_VERSION=$(sed -n "$(sed -n "/^[[:blank:]]*VA_VERSION[^_]/=" vasdk/VaConfig.gradle)p" vasdk/VaConfig.gradle | awk -F '=' '{print $NF}' | sed "s/[[:blank:]]*[\"']*//g")
cwd=$(cd "$(dirname "$0")"; pwd)
apk_release_path=""

# 重置 app build.gradle
git checkout app/build.gradle
# 重置 module_common build.gradle
git checkout module_common/build.gradle
# 重置 module_sensors_data build.gradle
git checkout module_sensors_data/build.gradle

# 开启 mapping 上传
if [[ "$OSTYPE" == "darwin"* ]]; then
  sed -i '' '1 a plugins { id "io.sentry.android.gradle" version "3.7.0" }' app/build.gradle
  sed -i '' 's/var isTestBuild = true/var isTestBuild = false/g' module_sensors_data/build.gradle
else
  sed -i '1 a plugins { id "io.sentry.android.gradle" version "3.7.0" }' app/build.gradle
  sed -i 's/var isTestBuild = true/var isTestBuild = false/g' module_sensors_data/build.gradle
fi

if [[ $buildType == "debug" ]]; then
  build_time_without_divider=$(TZ=Asia/Shanghai date +'%Y%m%d%H%M')L
  if [[ "$OSTYPE" == "darwin"* ]]; then
    sed -i '' 's/buildConfigField "long", "BUILD_TIME", "0"/buildConfigField "long", "BUILD_TIME", '"\"${build_time_without_divider}\""'/g' module_common/build.gradle
  else
    sed -i 's/buildConfigField "long", "BUILD_TIME", "0"/buildConfigField "long", "BUILD_TIME", '"\"${build_time_without_divider}\""'/g' module_common/build.gradle
  fi
fi

./gradlew --stop
./gradlew clean

OPTIONS=$(getopt -o '' -l config_id:,sdk_platform:,sdk_version:,app_id:,app_name:,channel:,activate_reporting_ratio:,first_launch_jump:,output:,unix_timestamp:,sdk_type:,keypoint_action_reporting:,va_version:, -- "$@")

eval set -- "$OPTIONS"

while true; do
  case "$1" in
    --config_id) config_id="$2"; shift 2;;
    --sdk_platform) sdk_platform="$2"; shift 2;;
    --sdk_version) sdk_version="$2"; shift 2;;
    --channel) channel="$2"; shift 2;;
    --activate_reporting_ratio) activate_reporting_ratio="$2"; shift 2;;
    --first_launch_jump) first_launch_jump="$2"; shift 2;;
    --output) output="$2"; shift 2;;
    --unix_timestamp) unix_timestamp="$2"; shift 2;;
    --app_id) app_id="$2"; shift 2;;
    --app_name) app_name="$2"; shift 2;;
    --sdk_type) sdk_type="$2"; shift 2;;
    --keypoint_action_reporting) keypoint_action_reporting="$2"; shift 2;;
    --va_version) va_version="$2"; shift 2;;
    --) shift; break;;
    *) echo "Invalid option: $1" >&2; exit 1;;
  esac
done

mkdir -p $output

function updateChannelIfNeeded {
    if [ "${channel}" != "" ]; then
        java -jar ${cwd}/ApkChannelPackage.jar put -c $channel $1 release
        rm $1
        rm -r ./app/build/outputs/apk
        find . -type f -name "*.apk" -exec mv {} "${apk_release_path}" \;
    fi
}



# 保存 config_id
if [ "${config_id}" != "" ]; then
    sed -i "s/String CONFIG_ID = \"\"/String CONFIG_ID = \"${config_id}\"/g" app/build.gradle
fi

# 是否使用默认渠道 SDK （目前仅快手可用）
if [ "${sdk_type}" == "subpackage" ]; then
    sed -i "s/boolean USE_DEFAULT_CHANNEL_SDK = true/boolean USE_DEFAULT_CHANNEL_SDK = false/g" app/build.gradle
fi

# 保存 first_launch_jump
if [ "${first_launch_jump}" != "" ]; then
    sed -i "s/String FIRST_LAUNCH = \"\"/String FIRST_LAUNCH = \"${first_launch_jump}\"/g" app/build.gradle
fi

# 保存快手 app_id
if [ "${app_id}" != "" ]; then
    sed -i "s/String SDK_APP_ID = \"\"/String SDK_APP_ID = \"${app_id}\"/g" app/build.gradle
fi

# 保存快手 app_name
if [ "${app_name}" != "" ]; then
    sed -i "s/String SDK_APP_NAME = \"\"/String SDK_APP_NAME = \"${app_name}\"/g" app/build.gradle
fi

# 保存推广时上报关键行为事件的游戏类型
if [ "${keypoint_action_reporting}" != "" ]; then
    sed -i "s/String CORE_EVENT_GAME_CATEGORY = \"\"/String CORE_EVENT_GAME_CATEGORY = \"${keypoint_action_reporting}\"/g" app/build.gradle
fi

# 是否选择了 sdk 类型
if [ "${sdk_platform}" != "" ]; then
    apk_release_path="${output}/${PACKAGE_NAME}_${versionName}_${versionCode}_${channel}_${MODULE_VERSION}_${va_version}_${sdk_type}_${sdk_platform}_${sdk_version}_${unix_timestamp}.apk"
    if [ "${activate_reporting_ratio}" == "" ]; then
        activate_reporting_ratio="100"
    fi
        # 调整上报比例
    sed -i "s/int ACTIVATE_REPORTING_RATIO = 100/int ACTIVATE_REPORTING_RATIO = ${activate_reporting_ratio}/g" app/build.gradle

    sed -i "s/String SDK_VERSION = \"\"/String SDK_VERSION = \"${sdk_version}\"/g" app/build.gradle

    # 头条包
    if [ "${sdk_platform}" == "toutiao" ]; then
        if [ "${sdk_version}" == "5.3.0" ]; then
            sed -i "s/bytedanceApplog = \"6.16.3\"/bytedanceApplog = \"${sdk_version}\"/g" dependencies.gradle
            rm app/src/tea/java/com/gh/gamecenter/TeaHelper.kt
            mv app/src/tea/java/com/gh/gamecenter/TeaHelper app/src/tea/java/com/gh/gamecenter/TeaHelper.kt
        else
            sed -i "s/bytedanceApplog = \"6.16.3\"/bytedanceApplog = \"${sdk_version}\"/g" dependencies.gradle
        fi

        ./gradlew aTCR -I init.gradle

        echo "${sdk_version}_${activate_reporting_ratio}_光环助手_${versionName}_${versionCode}_头条推广包_${git_sha}_${build_time}"

        cp -R app/build/outputs/apk/teaCn/release/app-tea-cn-release.apk "${apk_release_path}"
        fi
    # 广点通包
    if [ "${sdk_platform}" == "guangdiantong" ]; then
        # 广点通 SDK 执行 ASM 后处理后会有问题
        ./gradlew aGCR

        echo "光环助手_${versionName}_${versionCode}_广点通推广包_${git_sha}_${build_time}"
        cp -R app/build/outputs/apk/gdtCn/release/app-gdt-cn-release.apk "${apk_release_path}"
    fi
    # 快手包
    if [ "${sdk_platform}" == "kuaishou" ]; then
        ./gradlew aKCR -I init.gradle

        echo "光环助手_${versionName}_${versionCode}_快手推广包_${git_sha}_${build_time}"
        cp -R app/build/outputs/apk/kuaishouCn/release/app-kuaishou-cn-release.apk "${apk_release_path}"
    fi
    # 神马包
    if [ "${sdk_platform}" == "shenma" ]; then
        ./gradlew aSCR -I init.gradle

        echo "光环助手_${versionName}_${versionCode}_神马推广包_${git_sha}_${build_time}"
        cp -R app/build/outputs/apk/smCn/release/app-sm-cn-release.apk "${apk_release_path}"
    fi
    updateChannelIfNeeded "${apk_release_path}"

else
    apk_release_path="${output}/${PACKAGE_NAME}_${versionName}_${versionCode}_${MODULE_VERSION}_${va_version}_${unix_timestamp}_${buildType}.apk"

    if [[ $buildType == "debug" ]]; then
        ./gradlew :app:assembleInternalCnRelease -I init.gradle
        cp -R app/build/outputs/apk/internalCn/release/app-internal-cn-release.apk "${apk_release_path}"
    else
        ./gradlew :app:assemblePublishCnRelease -I init.gradle
        cp -R app/build/outputs/apk/publishCn/release/app-publish-cn-release.apk "${apk_release_path}"
    fi

fi

# 重置 app build.gradle
git checkout app/build.gradle
# 重置 module_common build.gradle
git checkout module_common/build.gradle
# 重置 module_sensors_data build.gradle
git checkout module_sensors_data/build.gradle