#!/usr/bin/env bash

export PUBLISH_BRANCH=${PUBLISH_BRANCH:-master}

# Signing Apps
if [ "$TRAVIS_BRANCH" == "$PUBLISH_BRANCH" ]; then
    echo "Push to master branch detected, signing the app..."
    cp ./app/build/outputs/apk/app-release-unsigned.apk ./app/build/outputs/apk/app-release-unaligned.apk
    jarsigner -verbose -tsa http://timestamp.comodoca.com/rfc3161 -sigalg SHA1withRSA -digestalg SHA1 -keystore scripts/key.jks -storepass $STORE_PASS -keypass $KEY_PASS ./app/build/outputs/apk/app-release-unaligned.apk $ALIAS
    ${ANDROID_HOME}/build-tools/25.0.3/zipalign -v -p 4 ./app/build/outputs/apk/app-release-unaligned.apk ./app/build/outputs/apk/app-release.apk

    # Publishing App
    echo "Publishing app to Play Store..."
    gem install fastlane
    fastlane supply --apk ./app/build/outputs/apk/app-release.apk --track alpha --json_key scripts/fastlane.json --package_name $PACKAGE_NAME
fi

# Create a new folder and copy the builded apk to there
mkdir $HOME/work_new
cp -rf ./app/build/outputs/apk/ $HOME/work_new

git config --global user.email "no-reply@travis-ci.org"
git config --global user.name "apt-bot"

# Clone the repo on apk branch after going to $HOME
cd $HOME
git clone --quiet --branch=apk https://apt-bot:$BOT_TOKEN@github.com/fossasia/loklak_wok_android  apks > /dev/null

# Switch to the repository and checkout to an orphan branch
cd apks
git checkout --orphan temp

# Delete the previous apks and copy new apks
rm -rf ./work_new
cp -rf $HOME/work_new/ ./

# Add and commit the files
git add $HOME/work_new/apk/*.apk
git commit --message "Apk update for build:$TRAVIS_BUILD_NUMBER | Generated by Travis CI --skip-ci"

# Delete the previous branch and rename the new branch
git branch -D apk
git branch -m apk

# Push to the branch apk
git push origin apk --force --quiet> /dev/null
