#!/usr/bin/env bash
# *****************************************************************************
# @author CsHeng
# @2017.9.13 init
#
# 处理tinker patch包，默认以最新的包作为基线包来出包
#
#
# *****************************************************************************

# get current shell absolute dir
CWD=$(cd "$(dirname "$0")"; pwd)

source ${CWD}/tinker_env.sh

# 如果git代码已经提交了，目的是为了确认git commit id是能作为一个可追踪的tinkerId
cd ${CWD}
if [ -n "$(git status --porcelain)" ]; then
    echo "Please make sure that you commit your code before release "
    exit 0
fi
cd ${OLDPWD}

path_dir=`grep -r TINKER_BASE_APK_DIR ${GRADLE_FILE}| awk -F '=' '{print $2}'`
path_base=`echo ${path_dir} | awk -F '_' '{print $1}'`
git_sha_old=`echo ${path_dir} | awk -F '_' '{print $2}'`
git_sha_new=`git rev-parse --short HEAD`
patch_dir=${APP_TINKER_BASE}/${path_dir}/patch/${git_sha_new}

# dir exists, already patched
if [ -d "${patch_dir}" ]; then
    echo "git sha has already patched, skip patch."
    exit 0
else
    echo "git sha has no history patch files, starting patch..."
    if [ "${git_sha_new}" == "${git_sha_old}" ]; then
        echo "new git sha same as old git sha, skip patch."
        exit 0
    fi
fi

echo ${path_dir} ${path_base} ${git_sha_old} ${git_sha_new}

echo "enabling tinker..."

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

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

echo ${CMD_GRADLE_SYNC}
${CMD_GRADLE_SYNC}

mkdir -p ${TINKER_BAK_APK_BASE}/${path_dir}/
echo "cp -R ${APP_TINKER_BASE}/${path_dir}/. ${TINKER_BAK_APK_BASE}/${path_dir}"
cp -R ${APP_TINKER_BASE}/${path_dir}/. ${TINKER_BAK_APK_BASE}/${path_dir}

echo ${CMD_GRADLE_PATCH}
${CMD_GRADLE_PATCH}

echo "copying back patch files in case that files have been cleaned..."
mkdir -p ${patch_dir}
cp -R ${PATCH_OUTPUT}/. ${patch_dir}

echo "disabling tinker"

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

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

# remove tmp file
rm ${GRADLE_FILE}.bak

echo ${CMD_GRADLE_SYNC}
${CMD_GRADLE_SYNC}



