#!/bin/bash
# 上传 ipa 到蒲公英

# echo util
readonly COLOR_Cyan=''
readonly COLOR_Red=''
readonly COLOR_Default=''

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

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

echo_log "===== 打包完成，开始上传到蒲公英 ====="

NOW=$(date +"%Y_%m_%d_%H_%M_%S")
EBIZ_APK_PATH=$1
EBIZ_ENV=$2
EBIZ_APP_Build_Version=$3
PGY_API_KEY=$4
PGY_USER_KEY=$5
DD_HOST_URL=$6
CURRENT_DIR=$(cd "$(dirname "$0")"; pwd)
PROJECT_PATH=$(dirname $(cd "$(dirname "$0")"; pwd))

if [ ! -f "${EBIZ_APK_PATH}" ]; then
    echo_error "${EBIZ_APK_PATH} 文件不存在"
    exit 1
fi  

if [ "$?" -ne "0" ]; then
    echo_error "upload error"
    exit 1
fi

PGY_UPLOAD_SERVER="https://qiniu-storage.pgyer.com/apiv1/app/upload"
PGY_password="$(($RANDOM%9999+1111))"
PGY_upload_log="${EBIZ_ENV}_${NOW},${DD_MESSAGE}"

# 推送到钉钉机器人时显示打包的版本号
APK_INFO=$(aapt d badging $EBIZ_APK_PATH | grep package)
APK_INFO=(${APK_INFO/ / })
VERSION=(${APK_INFO[3]/=/ })
VERSION=${VERSION[1]//\'/}

APK_INFO=$(aapt d badging $EBIZ_APK_PATH | grep application-label:)
APK_INFO=(${APK_INFO/:/ })
EBIZ_APP_Name=${APK_INFO[1]//\'/}
EBIZ_Version="${VERSION}(${EBIZ_APP_Build_Version})"

# echo_log ${EBIZ_APP_Name}
# echo_log ${EBIZ_Version}
# echo_log ${PGY_password}

# 上传到蒲公英，并接收 Response
PGY_RESPONSE=`curl -F "file=@/${EBIZ_APK_PATH}" -F "uKey=${PGY_USER_KEY}" -F "_api_key=${PGY_API_KEY}" -F installType=2 -F password="${PGY_password}" -F "updateDescription=${PGY_upload_log}" ${PGY_UPLOAD_SERVER}`
RESPONSE=${PGY_RESPONSE//\\n/}

RESPONSE_CODE=$(echo $RESPONSE | jq '.code')
DD_ICON_URL=$(echo $RESPONSE | jq '.data.appIcon')/120
DD_DOWN_URL=$(echo $RESPONSE | jq '.data.appShortcutUrl')

if [ $RESPONSE_CODE -ne 0 ]; then
    echo_error "upload error"
    exit 1
fi

# (以上调试完成后，再打开以下注释)
if [ $# -eq 6 ]; then
    echo "${EBIZ_Version} ${EBIZ_APP_Name} ${EBIZ_ENV} ${DD_ICON_URL//\"/} ${DD_DOWN_URL//\"/} ${DD_HOST_URL} ${PGY_password}"
    python3 ${CURRENT_DIR}/auto_push_ding_talk.py ${EBIZ_Version} ${EBIZ_APP_Name} ${EBIZ_ENV} ${DD_ICON_URL//\"/} ${DD_DOWN_URL//\"/} ${DD_HOST_URL} ${PGY_password}
fi




