#!/usr/bin/env bash
# *****************************************************************************
# @author CsHeng
# @2017.9.14 init
#
# 处理tinker打包的事情：
# 1、启用tinker标志位
# 2、打出基线包，修改tinker base apk path
# 3、禁用tinker标志位
#
# *****************************************************************************

# get current shell absolute dir
CWD=$(cd "$(dirname "$0")"; pwd)
if [ -n "$(git status --porcelain)" ]; then
    echo "Please make sure that you commit your code before release "
    exit 0
fi
source ${CWD}/tinker_env.sh

# 如果git代码已经提交了，目的是为了确认git commit id是能作为一个可追踪的tinkerId
cd ${CWD}

cd ${OLDPWD}

git_sha_new=`git rev-parse --short HEAD`

# dir exists, already patched
if [ -d ${APP_TINKER_BASE} ] && [ -n "$(ls ${APP_TINKER_BASE} | grep ${git_sha_new})" ]; then
    echo "git sha has already released: ${git_sha_new}, skip."
    exit 0
else
    echo "git sha has no history base files, starting release..."

    # 也就是tinkerId
    git_sha_old=`grep -r TINKER_ID ${GRADLE_FILE}| awk -F '=' '{print $2}'`

    if [ "${git_sha_new}" == "${git_sha_old}" ]; then
        echo "new git sha same as old git sha: ${git_sha_new}, skip patch."
        exit 0
    fi
fi

echo "enabling tinker..."

# enable tinker build
sed -i.bak "s/TINKER_ENABLE\=\(.*\)/TINKER_ENABLE\=1/g" ${GRADLE_FILE}

# remove old tinker Id
sed -i.bak "s/TINKER_ID\=\(.*\)/TINKER_ID\=/g" ${GRADLE_FILE}

echo ${CMD_GRADLE_SYNC}
${CMD_GRADLE_SYNC}

echo ${CMD_GRADLE_RELEASE}
${CMD_GRADLE_RELEASE}

# 然后app/build/bakApk/会有一个文件夹保存基线包版本的所有文件，这些文件是需要保存起来的，以便出bug的时候
# 由于默认的tinker support产生文件的规则都是以时间来判断的，那么我们做个排序，拿最新的为准

# get apk dir name
old_apk_dir=`ls -t ${TINKER_BAK_APK_BASE} | head -1`

dest_dir=${old_apk_dir}_${git_sha_new}

echo "saving patch base files...to ${dest_dir}"

mkdir -p ${APP_TINKER_BASE}/${dest_dir}
cp -R ${TINKER_BAK_APK_BASE}/${old_apk_dir}/. ${APP_TINKER_BASE}/${dest_dir}

echo "disabling tinker & set release old apk path"

# disable tinker
sed -i.bak "s/TINKER_ENABLE\=\(.*\)/TINKER_ENABLE\=/g" ${GRADLE_FILE}

# write tinker id
sed -i.bak "s/TINKER_ID\=\(.*\)/TINKER_ID\=${git_sha_new}/g" ${GRADLE_FILE}

# apk path
sed -i.bak "s/TINKER_BASE_APK_DIR\=\(.*\)/TINKER_BASE_APK_DIR\=${dest_dir}/g" ${GRADLE_FILE}

# remove tmp file
rm ${GRADLE_FILE}.bak

echo ${CMD_GRADLE_SYNC}
${CMD_GRADLE_SYNC}


