#!/usr/bin/env bash
#
# Copyright (C) 2019-Present A-Team Digital Solutions
#

clear
set -e

GAPPS_DIR="$ROM_PATH/vendor/gapps"

#
# Validate ROM path
#
if [[ -z "$ROM_PATH" ]]; then
    echo
    echo "ERROR: ROM_PATH Is Not Set."
    exit 1
fi
if [[ ! -d "$ROM_PATH" ]]; then
    echo
    echo "ERROR: ROM Source Directory Does Not Exist:"
    echo "$ROM_PATH"
    exit 1
fi
#
# Select MindTheGapps branch based on Android version
#
case "$ANDROID_VERSION" in
    16)
        GAPPS_BRANCH="baklava"
        echo
        echo "================================"
        echo "Syncing MindTheGapps ..."
        echo "Android 16 - Baklava"
        echo "================================"
        ;;
    17)
        GAPPS_BRANCH="cinnamonbun"
        echo
        echo "================================"
        echo "Syncing MindTheGapps ..."
        echo "Android 17 - Cinnamonbun"
        echo "================================"
        ;;
    *)
        echo
        echo "ERROR: Unsupported Android Version:"
        echo "$ANDROID_VERSION"
        echo
        echo "Supported Versions:"
        echo "  Android 16 - Baklava"
        echo "  Android 17 - Cinnamonbun"
        exit 1
        ;;
esac
#
# Remove existing GApps source
#
if [[ -d "$GAPPS_DIR" ]]; then
    echo
    echo "Removing Existing MindTheGapps Source:"
    echo "$GAPPS_DIR"
    rm -rf "$GAPPS_DIR"
fi
#
# Clone MindTheGapps
#
echo
echo "Cloning MindTheGapps:"
echo "Branch: $GAPPS_BRANCH"
echo "Destination: $GAPPS_DIR"
echo
git clone \
    --depth=1 \
    "https://github.com/MindTheGapps/vendor_gapps.git" \
    -b "$GAPPS_BRANCH" \
    "$GAPPS_DIR"
#
# Pull LFS assets
#
echo
echo "Pulling MindTheGapps LFS Assets ..."
#
# Enter GApps directory temporarily.
#
pushd "$GAPPS_DIR" >/dev/null
if ! git lfs pull; then
    echo
    echo "ERROR: Failed To Pull MindTheGapps LFS Assets."
    popd >/dev/null
    exit 1
fi
#
# Return to the directory we started in.
#
popd >/dev/null
echo
echo "================================"
echo "MindTheGapps Sync Complete!"
echo "================================"
echo
echo "Location:"
echo "$GAPPS_DIR"
