#!/bin/bash

# Functions borrowed or derived from
# Michael Bryant / Shadow53
# https://gitlab.com/Shadow53/android-zip-builder

REPO_FDROID="https://f-droid.org/repo"
REPO_GUARDIAN="https://guardianproject.info/fdroid/repo"
REPO_MICROG="https://microg.org/fdroid/repo"
REPO_NANOLX="https://nanolx.org/fdroid/repo"
REPO_BROMITE="https://fdroid.bromite.org/fdroid/repo"

# check dependencies
for dep in gawk curl sha256sum jq gzip; do
	if ! which ${dep} &>/dev/null; then
		echo "${dep} is not installed!"
		exit 1
	fi
done

index_update_required () {
	INDEX_FILE=${1}

	test ! -f ${INDEX_FILE} && return 0
	test $(stat --format=%Z ${INDEX_FILE}) -le $(($(date +%s) - 3600)) && return 0
	test "$(file -b ${INDEX_FILE})" == "empty" && return 0

	return 1
}

check_sha256sum () {
	INPUT="${1}"

	IN_CHECKSUM=""
	EX_CHECKSUM="${2}"

	case ${INPUT} in
		*.gz )
			IN_CHECKSUM=$(gzip -dc ${INPUT} 2>/dev/null | sha256sum | gawk '{print $1}')
		;;

		* )
			IN_CHECKSUM=$(sha256sum ${INPUT} 2>/dev/null | gawk '{print $1}')
		;;
	esac

	[[ ${IN_CHECKSUM} == ${EX_CHECKSUM} ]] && return 0 || return 1
}

update_index () {
	INDEX_JAR=${1}
	INDEX_JSON="${CWD}/data/$(basename ${INDEX_JAR} .jar).json"
	INDEX_REPO=${2}

	if index_update_required ${INDEX_JSON}; then
		curl -sSL -o "${INDEX_JAR}" "${INDEX_REPO}/index-v1.jar" || error " failed to update repo index"

		unzip -q ${INDEX_JAR} index-v1.json -d "${CWD}/data/"
		mv "${CWD}/data/index-v1.json" "${INDEX_JSON}"
		rm -f ${INDEX_JAR}
	fi
}

update_indices () {
	echo "+++ upating Repo Indices"
	echo " ++ F-Droid"
	update_index "${CWD}/data/$(awk -F/ '{print $3}' <<< ${REPO_FDROID}).index-v1.jar" "${REPO_FDROID}"

	echo " ++ Guardian Project"
	update_index "${CWD}/data/$(awk -F/ '{print $3}' <<< ${REPO_GUARDIAN}).index-v1.jar" "${REPO_GUARDIAN}"

	echo " ++ microG"
	update_index "${CWD}/data/$(awk -F/ '{print $3}' <<< ${REPO_MICROG}).index-v1.jar" "${REPO_MICROG}"

	echo " ++ Nanolx"
	update_index "${CWD}/data/$(awk -F/ '{print $3}' <<< ${REPO_NANOLX}).index-v1.jar" "${REPO_NANOLX}"

	echo " ++ Bromite"
	update_index "${CWD}/data/$(awk -F/ '{print $3}' <<< ${REPO_BROMITE}).index-v1.jar" "${REPO_BROMITE}"
}

grab_apk_from_repo () {
	case "${1}" in
		fdroid )
			REPO=${REPO_FDROID}
			REPO_P="F-Droid"
		;;

		guardian )
			REPO=${REPO_GUARDIAN}
			REPO_P="Guardian Project"
		;;

		microg )
			REPO=${REPO_MICROG}
			REPO_P="microG"
		;;

		nanolx )
			REPO=${REPO_NANOLX}
			REPO_P="Nanolx"
		;;

		bromite )
			REPO=${REPO_BROMITE}
			REPO_P="Bromite"
		;;
	esac

	DOMAIN="$(awk -F/ '{print $3}' <<< ${REPO})"
	INDEX_FILE="${CWD}/data/${DOMAIN}.index-v1.json"

	PKG_NAME="${2}"

	if [ -z "${5}" ]; then
		APK_NAME="$(jq -r --arg pkg "${PKG_NAME}" '.packages[$pkg][0].apkName' ${INDEX_FILE})"
		SHA_SUM="$(jq -r --arg pkg "${PKG_NAME}" '.packages[$pkg][0].hash' ${INDEX_FILE})"
	else
		APK_NAME="$(jq -r --arg pkg "${PKG_NAME}" --arg arch "${5}" '[.packages[$pkg][] | select (.nativecode[]==$arch).apkName][0]' ${INDEX_FILE})"
		SHA_SUM="$(jq -r --arg pkg "${PKG_NAME}" --arg arch "${5}" '[.packages[$pkg][] | select (.nativecode[]==$arch).hash][0]' ${INDEX_FILE})"
	fi

	case "${PKG_NAME}" in
		com.android.webview )
			APK_DEST="${CWD}/BromiteWebView/system/${3}/${4}"
		;;

		net.osmand.plus | net.osmand.srtmPlugin.paid )
			APK_DEST="${CWD}/OsmAnd/system/${3}/${4}"
		;;

		com.google.android.gms )
			# XXX select mapbox build in official microG repo
			APK_NAME="$(jq -r --arg pkg "${PKG_NAME}" '.packages[$pkg][0] | select (.versionName | contains("mapbox")).apkName' ${INDEX_FILE})"
			SHA_SUM="$(jq -r --arg pkg "${PKG_NAME}" '.packages[$pkg][0] | select (.versionName | contains("mapbox")).hash' ${INDEX_FILE})"
			APK_DEST="${CWD}/Full/system/${3}/${4}"
		;;

		* )
			APK_DEST="${CWD}/Full/system/${3}/${4}"
		;;
	esac

	APK_URL="${REPO}/${APK_NAME}"

	if check_sha256sum "${APK_DEST}/${4}.apk.gz" "${SHA_SUM}"; then
		echo -e "\nUp-to-Date from ${REPO_P} : ${4}.apk"
	else	echo -e "\nUpdating from ${REPO_P}   : ${4}.apk"
		mkdir -p "${APK_DEST}"
		rm -f "${APK_DEST}/${4}.apk.gz"
		curl -sSL -o "${APK_DEST}/${4}.apk" "${APK_URL}"

		if check_sha256sum "${APK_DEST}/${4}.apk" "${SHA_SUM}"; then
			echo "	SHA256 hash of ${4}.apk is correct"
			gzip "${APK_DEST}/${4}.apk"
		else	echo -e "	SHA256 hash of ${4}.apk is wrong!\
			\n	expected	: ${SHA_SUM}\
			\n	got		: ${IN_CHECKSUM}"
			rm -f "${APK_DEST}/${4}.apk"
		fi
	fi
}

grab_apk_from_url () {
	APK_URL="${1}"
	APK_DEST="${CWD}/Full/system/${2}/${3}"

	rm -f "${APK_DEST}/${3}.apk.gz"

	if [[ -f "${APK_DEST}/${3}.apk" ]]; then
		echo -e "\nUpdating from URL         : ${3}.apk"
	else    echo -e "\nDownloading from URL      : ${3}.apk"
		mkdir -p "${APK_DEST}"
	fi

	echo "  Checking SHA256 hash not (yet) supported"

	curl -sSL -o "${APK_DEST}/${3}.apk" "${APK_URL}" || \
		rm -f "${APK_DEST}/${3}.apk"

	if [[ -f "${APK_DEST}/${3}.apk" ]]; then
		gzip "${APK_DEST}/${3}.apk"
	else	echo "error downloading ${3}"
	fi
}

grab_apk_from_github () {
	APK_URL="$(curl -s -N "https://api.github.com/repos/${1}/releases" | \
		gawk -F\" '/browser_download_url.*apk/{print $4 ; exit}')"
	APK_DEST="${CWD}/Full/system/${2}/${3}"

	rm -f "${APK_DEST}/${3}.apk.gz"

	if [[ -f "${APK_DEST}/${3}.apk" ]]; then
		echo -e "\nUpdating from GitHub      : ${3}.apk"
	else	echo -e "\nDownloading from GitHub   : ${3}.apk"
		mkdir -p "${APK_DEST}"
	fi



	echo "	Checking SHA256 hash not (yet) supported"

	curl -sSL -o "${APK_DEST}/${3}.apk" "${APK_URL}" || \
		rm -f "${APK_DEST}/${3}.apk"

	if [[ -f "${APK_DEST}/${3}.apk" ]]; then
		gzip "${APK_DEST}/${3}.apk"
	else	echo "error downloading ${3}"
	fi
}

grab_apk_from_gitlab () {
	APK_URL="https://gitlab.com$(curl -s -N "https://gitlab.com/${1}/-/tags" | \
		gawk -F\" '/\.apk/{print $6 ; exit}')"
	APK_DEST="${CWD}/Full/system/${2}/${3}"

	rm -f "${APK_DEST}/${3}.apk.gz"

	if [[ -f "${APK_DEST}/${3}.apk" ]]; then
		echo -e "\nUpdating from GitLab      : ${3}.apk"
	else	echo -e "\nDownloading from GitLab   : ${3}.apk"
		mkdir -p "${APK_DEST}"
	fi

	echo "	Checking SHA256 hash not (yet) supported"

	curl -sSL -o "${APK_DEST}/${3}.apk" "${APK_URL}" || \
		rm -f "${APK_DEST}/${3}.apk"

	if [[ -f "${APK_DEST}/${3}.apk" ]]; then
		gzip "${APK_DEST}/${3}.apk"
	else	echo "error downloading ${3}"
	fi
}

grab_apk_from_ogapps () {
	case "${1}" in
		"com.google.android.syncadapters.calendar" )
			APK_URL="https://gitlab.opengapps.org/opengapps/all/raw/master/${2}/${1}/15/nodpi/2015080710.apk"
		;;

		* )
			APK_URL="https://gitlab.opengapps.org/opengapps/all/raw/master/${2}/${1}/${4}/nodpi/${4}.apk"
		;;
	esac

	case "${4}" in
		19 ) API_LETTER=K ;;
		21 ) API_LETTER=L ;;
		23 ) API_LETTER=M ;;
		24 ) API_LETTER=N ;;
		26 ) API_LETTER=O ;;
		28 ) API_LETTER=P ;;
	esac

	APK_DEST="${CWD}/Full/gsync/${API_LETTER}/${2}/${3}"

	if [[ -f "${APK_DEST}/${3}.apk.gz" ]]; then
		echo -e "\nUpdating from OpenGApps   : ${3}.apk [${API_LETTER}]"
		rm -f "${APK_DEST}/${3}.apk.gz"
	else	echo -e "\nDownloading from OpenGApps: ${3}.apk [${API_LETTER}]"
		mkdir -p "${APK_DEST}"
	fi

	echo "	Checking SHA256 hash not (yet) supported"

	curl -sSL -o "${APK_DEST}/${3}.apk" "${APK_URL}" || \
		rm -f "${APK_DEST}/${3}.apk"

	[ -f "${APK_DEST}/${3}.apk" ] && gzip "${APK_DEST}/${3}.apk"
}

grab_lib_from_ogapps () {
	case "${3}" in
		arm | x86 )	 LIBD=lib   ;;
		arm64 | x86_64 ) LIBD=lib64 ;;
	esac

	LIB_URL="https://gitlab.opengapps.org/opengapps/${3}/raw/master/${LIBD}/${2}/${1}?inline=false"
	SWP_DEST="${CWD}/Full/swipe/${3}"

	if [[ "${4}" == "true" ]]; then
		LIB_DEST="${SWP_DEST}/${1}_${2}"
	else	LIB_DEST="${SWP_DEST}/${1}"
	fi

	if [[ -f "${LIB_DEST}" ]]; then
		echo -e "\nUpdating from OpenGApps   : ${1} [${2}:${3}]"
	else	echo -e "\nDownloading from OpenGApps: ${1} [${2}:${3}]"
		mkdir -p "${SWP_DEST}"
	fi

	echo "	Checking SHA256 hash not (yet) supported"

	curl -sSL -o "${LIB_DEST}" "${LIB_URL}" || \
		rm -f "${LIB_DEST}"
}

grab_patches () {
	BASE_URL="https://github.com/Lanchon/haystack/blob/master/patches"

	PATCH_URL="${BASE_URL}/${1}?raw=true"
	PATCH_DST="${CWD}/patcher/dexpatcher/${2}"

	echo -e "\nUpdating from Haystack   : ${2}"
	echo "	Checking SHA256 hash not (yet) supported"

	curl -sSL -o "${PATCH_DST}" "${PATCH_URL}" || \
		rm -f "${PATCH_DST}"
}
