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

version=$(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')
build_time_without_divider=$(TZ=Asia/Shanghai date +'%Y%m%d%H%M')L

post_init_script=init.internal.gradle

git checkout module_common/build.gradle
git checkout gradle.properties

./gradlew --stop
./gradlew clean

sed -i 's/buildConfigField "long", "BUILD_TIME", "0"/buildConfigField "long", "BUILD_TIME", '"\"${build_time_without_divider}\""'/g' module_common/build.gradle

# 生成git log文本
git log --pretty=format:'%s' --max-count=20 --no-merges > app/src/main/assets/gitlog.txt

BUILD_VARIANT_REGION=cn
BUILD_PUSH_TYPE=jg

# 添加 -c 代表启用 compose setting 模块
# 添加 -r 指定区域，可选值: cn: 中国大陆 gat: 港澳台
# 添加 -p 指定推送类型 可选值: jg: 极光推送 ac: 阿里云推送
while getopts "cr:p:" arg
do
    case ${arg} in
        c)
            sed -i '260 a implementation(project(\x27:module_setting_compose\x27)) { exclude group: \x27androidx.swiperefreshlayout\x27 }' app/build.gradle
        ;;
        r)
            case $OPTARG in
                gat) BUILD_VARIANT_REGION=gat
                ;;
                *) BUILD_VARIANT_REGION=cn
                ;;
            esac
        ;;
        p)
            case $OPTARG in
                jg) BUILD_PUSH_TYPE=jg
                ;;
            *) BUILD_PUSH_TYPE=ac
                ;;
            esac
        ;;
    esac
done

./gradlew assembleInternal${BUILD_VARIANT_REGION^}Release -I ${post_init_script} -PBUILD_PUSH_TYPE=${BUILD_PUSH_TYPE}
mv app/build/outputs/apk/internal${BUILD_VARIANT_REGION^}/release/app-internal-${BUILD_VARIANT_REGION}-release.apk app/build/tmp/${version}-${versionCode}-test-${build_time}.apk

git checkout app/build.gradle
git checkout module_common/build.gradle
git checkout gradle.properties
rm app/src/main/assets/gitlog.txt

# 上传 APK 文件 (仅接入 dev 分支)
echo $1

if [[ $1 == "dev"* ]]; then
    declare startCommitSha="$2"
    declare endCommitSha="$3"
    declare apkFile="./app/build/tmp/${version}-${versionCode}-test-${build_time}.apk"
    declare uploadUrl="https://app-manager.shanqu.cc/app/upload?auth_token=7798334f70358b71a7243892faf97ee0"
    echo "uploading apk file:  ${apkFile}"
    if [ ! $startCommitSha ]; then
      curl -F "file=@${apkFile};type=application/octet-stream" "${uploadUrl}"
    else
      git log --pretty=format:"%s (%an) [%h](https://git.shanqu.cc/halo/android/assistant-android/-/commits/%H)" --no-merges $startCommitSha..$endCommitSha >> changelog.log
      curl -F "file=@${apkFile};type=application/octet-stream" -F "changelog=@./changelog.log;type=application/octet-stream" "${uploadUrl}"
      rm changelog.log
    fi
fi
