#!/bin/bash

# Created by G.Capelli (BasicAirData) on 28/10/2020

# The script reads the "versionName" property from gradle file and execute some tasks
# in order to prepare apks and zipped source files for the new release.
# It performs the following tasks:

# 1) it brings the signed app-release.apk and copy it into apk folder with the right name
# 2) it substitutes the GPSLogger-latest.apk with the new one
# 3) it zips the source code and places the archive into the sourcecode folder

# This script is made to be executed after the building of the signed apk file,
# and must be executed from inside the GPSLogger project Folder.


currentpath=$(pwd)
if [[ ${currentpath} != *"GPSLogger"* ]];then
	# currentpath does not contain "GPSLogger"
	echo GPSLogger Project Folder not found, exiting...
	exit 1
fi

gpsloggerpath="${currentpath%GPSLogger*}GPSLogger/"
echo "Project Folder: ${gpsloggerpath}"
cd ${gpsloggerpath}



# Read the versionName from gradle file

ver=$(grep -n "versionName " ./app/build.gradle | cut -d"'" -f 2)

if [ -z "$ver" ]; then
	echo Version number not found, exiting...
	exit 1
fi
echo "Preparing GPSLogger v${ver}:"

apkrelease="apk/GPSLogger-${ver}.apk"
apklatest="apk/GPSLogger-latest.apk"
zipsource="sourcecode/GPSLogger-${ver} - Source.zip"



# 1) Copy the APK file (generated by Android Studio
#    with "Generate Signed Bundle / APK" command) into ./apk

rm "${apkrelease}" > /dev/null 2>&1
cp ./app/release/app-release.apk "${apkrelease}"
echo "- Created:             ${apkrelease}"



# 2) Update the latest APK file

rm "${apklatest}" > /dev/null 2>&1
cp "${apkrelease}" "${apklatest}"
echo "- Updated:             ${apklatest}"



# 3) Zip the Source into ./sourcecode folder

rm "${zipsource}" > /dev/null 2>&1
zip -r "${zipsource}" ./app/src ./app/*.* > /dev/null 2>&1
echo "- Zipped source into:  ${zipsource}"
