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

set -e

: "${ROM_PATH:?ROM_PATH not set}"
: "${ROM_VENDOR_NAME:?ROM_VENDOR_NAME not set}"
: "${APN_VARIANT:?APN_VARIANT not set}"
: "${A_TEAM_SETUP_LOCATION:?A_TEAM_SETUP_LOCATION not set}"

CUSTOM_APN_DIR="$ROM_PATH/device/A-Team/Custom_APN"
CUSTOM_APN_XML="$CUSTOM_APN_DIR/A-Team.xml"
SOURCE_APN_XML="$A_TEAM_SETUP_LOCATION/Custom_APN/A-Team.xml"
SOURCE_ANDROID_MK="$A_TEAM_SETUP_LOCATION/Custom_APN/Android.mk"
SOURCE_ANDROID_BP="$ROM_PATH/vendor/apn"
APN_ANDROID_BP="$SOURCE_ANDROID_BP/Android.bp"
LEGACY_ANDROID_MK="$ROM_PATH/vendor/$ROM_VENDOR_NAME/prebuilt/common/Android.mk"

echo "=================================================="
echo " A-Team APN Configuration"
echo "=================================================="
echo

mkdir -p "$CUSTOM_APN_DIR"
if [[ -f "$SOURCE_APN_XML" ]]; then
    cp -f "$SOURCE_APN_XML" "$CUSTOM_APN_XML"
else
    echo "WARNING: A-Team Custom APN XML Not Found:"
    echo "  $SOURCE_APN_XML"
fi
if [[ "$APN_VARIANT" == "1" ]]; then
    echo "APN Selection: Custom"
    cp -f "$CUSTOM_APN_XML" "$SOURCE_ANDROID_BP"
else
    echo "APN Selection: Default"
    rm -f $SOURCE_ANDROID_BP/A-Team.xml
fi

install_legacy_mk() {
    echo
    echo "Detected APN Build System: Legacy Android.mk"
    rm -f "$CUSTOM_ANDROID_BP"

    if [[ ! -f "$SOURCE_ANDROID_MK" ]]; then
        echo "WARNING: A-Team Legacy Android.mk Not Found:"
        echo "  $SOURCE_ANDROID_MK"
        return 1
    fi

    mkdir -p "$(dirname "$LEGACY_ANDROID_MK")"
    cp -f "$SOURCE_ANDROID_MK" "$LEGACY_ANDROID_MK"
    echo "Installed Legacy A-Team Android.mk:"
    echo "  $LEGACY_ANDROID_MK"
}

if [[ -f "$LEGACY_ANDROID_MK" ]]; then
    install_legacy_mk
fi

echo
echo "A-Team Custom APN Configuration Complete."
echo
