BUILD_ENV=$1
BUILD_TYPE=$2
PGY_API_KEY=$3
PGY_USER_KEY=$4
DD_HOST_URL=$5
DD_PUSH=$6
JIAGU_AK=$7
JIAGU_SK=$8
KS_ALIA=$9
KS_PASS=${10}

COLOR_Cyan=''
COLOR_Red=''
COLOR_Default=''

function echo_log() {
    echo "${COLOR_Cyan}$1${COLOR_Default}"
}

function echo_error() {
    echo "${COLOR_Red}$1${COLOR_Default}"
}

# 计时
SECONDS=0

PROJECT_DIR=$(dirname $(cd "$(dirname "$0")"; pwd))

echo_log "============ config list =============="
echo_log "1 build configuration = ${BUILD_ENV} ${BUILD_TYPE}"
echo_log "2 workspace path = ${PROJECT_DIR}"
echo_log "3 gradle assemble${BUILD_ENV}${BUILD_TYPE}"
echo_log "======================================="

# 打包命令
cd ${PROJECT_DIR}
gradle clean
gradle assemble${BUILD_ENV}${BUILD_TYPE}

JKS_PATH=($(find ${PROJECT_DIR} -name *.jks))
APK_PATH=($(find ${PROJECT_DIR}/app/build -name *.apk))
APK_INFO=$(aapt d badging $APK_PATH | grep package)
APK_INFO=(${APK_INFO/ / })
VERSION=(${APK_INFO[2]/=/ })
BUILD_NUMBER=${VERSION[1]//\'/}

echo_log "APK_PATH：${APK_PATH}"
echo_log "JKS_PATH：${JKS_PATH}"
echo_log "===== 打包耗时：${SECONDS}s ====="

${PROJECT_DIR}/apk_script/apkprotect -akey ${JIAGU_AK} -skey=${JIAGU_SK} -i ${APK_PATH} -o ${PROJECT_DIR}/app/build/jiagu.apk
echo_log "===== 加固耗时：${SECONDS}s ====="

apksigner sign --ks ${JKS_PATH} --ks-key-alias ${KS_ALIA}  --ks-pass pass:${KS_PASS} --key-pass pass:${KS_PASS} --out ${PROJECT_DIR}/app/build/sign.apk ${PROJECT_DIR}/app/build/jiagu.apk
echo_log "===== 签名耗时：${SECONDS}s ====="

rm -rf ${APK_PATH} && mv ${PROJECT_DIR}/app/build/sign.apk ${APK_PATH}

# 上传到蒲公英 (以上调试完成后，再打开以下注释)
if [ "yes" == "$DD_PUSH" ]; then
	sh ${PROJECT_DIR}/apk_script/auto_upload_pgy.sh ${APK_PATH} ${BUILD_ENV} ${BUILD_NUMBER} ${PGY_API_KEY} ${PGY_USER_KEY} ${DD_HOST_URL}
else
	sh ${PROJECT_DIR}/apk_script/auto_upload_pgy.sh ${APK_PATH} ${BUILD_ENV} ${BUILD_NUMBER} ${PGY_API_KEY} ${PGY_USER_KEY}
fi