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

MONA_SETUP_CHECK="${ROM_PATH}/device/A-Team/Mona-Setup.check"

# Select Android Repo Version 
if [[ $ANDROID_VERSION == "16" ]]; then
   # Set Device Source Branch Variables
   # Android 16
   SOURCE_BRANCH_PREFIX="lineage-"
   SOURCE_MAJOR_VERSION="23"
   SOURCE_MINOR_VERSION=".2"
# A-Team Rom Installer
elif [[ $ANDROID_VERSION == "17" ]]; then
   # Set Device Source Branch Variables
   # Android 17
   SOURCE_BRANCH_PREFIX="lineage-"
   SOURCE_MAJOR_VERSION="24"
   SOURCE_MINOR_VERSION=".0"
fi

BRANCH="${SOURCE_BRANCH_PREFIX}${SOURCE_MAJOR_VERSION}${SOURCE_MINOR_VERSION}"

set -e
echo  
echo "Syncing Mona Device Dependencies ..."
echo 
echo "Repo Branch: $BRANCH"
echo  
clone_repo() {
    local repo="$1"
    local path="$2"
    if [ -d "$path" ]; then
        echo "Skipping Existing: $path" 
    else
        echo "Cloning $repo -> $path ..." 
        mkdir -p "$(dirname "$path")"
        git clone --depth=1 -b "$BRANCH" "https://github.com/$repo.git" "$path" || {
            echo "FAILED: $repo"
        }
    fi
}
# Device
clone_repo "LineageOS/android_device_motorola_mona" \
           "device/motorola/mona"
echo 
echo 
clone_repo "LineageOS/android_device_motorola_sm7435-common" \
           "device/motorola/sm7435-common"
echo 
echo 
# Kernel
clone_repo "LineageOS/android_kernel_motorola_sm7435" \
           "kernel/motorola/sm7435"
echo 
echo
clone_repo "LineageOS/android_kernel_motorola_sm7435-modules" \
           "kernel/motorola/sm7435-modules"
echo 
echo 
clone_repo "LineageOS/android_kernel_motorola_sm7435-devicetrees" \
           "kernel/motorola/sm7435-devicetrees"
echo 
echo 
# Hardware
clone_repo "LineageOS/android_hardware_motorola" \
           "hardware/motorola"
echo 
echo 
# Vendor Blobs
clone_repo "TheMuppets/proprietary_vendor_motorola_mona" \
           "vendor/motorola/mona"
echo 
echo
clone_repo "TheMuppets/proprietary_vendor_motorola_sm7435-common" \
           "vendor/motorola/sm7435-common"
echo  
echo "Checking Vendor:"
ls vendor/motorola/mona 2>/dev/null || echo "Vendor Missing!" 
echo 
echo "Sync Finished." 
echo 

if [ -f "$MONA_SETUP_CHECK" ]; then
    echo
    echo "$DEVICE_DISPLAY_CODENAME Setup Already Run, Skipping Setup ..."
    echo
else
    echo
    echo "Starting $DEVICE_DISPLAY_CODENAME Device Tree Setup & Patching ..."
    echo 
    echo "Checking A-Team Device Addon:"
    ls $A_TEAM_SETUP_LOCATION 2>/dev/null || echo "A-Team Device Addon Missing! && exit 1"
    echo 
    # Check If Rom Uses Changelog & Hijack It If So For Custom Changelogs
    if [ -f $ROM_PATH/vendor/$ROM_VENDOR_NAME/tools/changelog ]; then
       # Copy Changelog Template Files
       echo "Copying Device Specific Changelog Templates ..."
       cp -r $A_TEAM_SETUP_LOCATION/Changelog/Changelog.txt.$DEVICE_DISPLAY_CODENAME $ROM_PATH/A-Team_Changelog/Changelog.txt.$DEVICE_DISPLAY_CODENAME
       echo 
       echo "1/1 ..."
       echo 
       sleep 3
    elif [ -f $ROM_PATH/vendor/$ROM_VENDOR_NAME/tools/changelog.sh ]; then
       # Copy Changelog Template Files
       echo "Copying Device Specific Changelog Templates ..."
       cp -r $A_TEAM_SETUP_LOCATION/Changelog/Changelog.txt.$DEVICE_DISPLAY_CODENAME $ROM_PATH/A-Team_Changelog/Changelog.txt.$DEVICE_DISPLAY_CODENAME
       echo 
       echo "1/1 ..."
       echo 
       sleep 3
    elif [ -f $ROM_PATH/vendor/$ROM_VENDOR_NAME/build/tools/changelog.sh ]; then
       # Copy Changelog Template Files
       echo "Copying Device Specific Changelog Templates ..."
       cp -r $A_TEAM_SETUP_LOCATION/Changelog/Changelog.txt.$DEVICE_DISPLAY_CODENAME $ROM_PATH/A-Team_Changelog/Changelog.txt.$DEVICE_DISPLAY_CODENAME
       echo 
       echo "1/1 ..."
       echo 
       sleep 3
    else
       echo "A-Team Custom Changelog NOT Supported By ROM ..."
       echo
    fi

    # Mona Setup
    ##########################################################################################################

    ## Patch BoardConfigCommon.mk
    #echo "Patching BoardConfigCommon.mk..."
    #echo ""
    #echo "1/1..."
    #echo ""
    #sed -i '\|COMMON_PATH := device/motorola/sm7435-common|a BUILD_BROKEN_ELF_PREBUILT_PRODUCT_COPY_FILES := true\nBUILD_BROKEN_DUP_RULES := true' device/motorola/sm7435-common/BoardConfigCommon.mk

    #sleep 3

    ## Patch BoardConfig.mk
    echo "Patching $DEVICE_DISPLAY_CODENAME BoardConfig.mk ..."
    #sed -i '/BOARD_SUPER_PARTITION_SIZE := 6710886400/ a BOARD_MOT_DYNAMIC_PARTITIONS_SIZE := 6706692096' $ROM_PATH/device/motorola/$DEVICE_CODENAME/BoardConfig.mk
    #echo 
    #echo "2/3 ..."
    #echo 
    #sleep 3
    patch_target_kernel_config() {
        local file="$1"
        local stock_cfg="$2"
        local ateam_cfg="$3"
        local tmp="${file}.tmp"
        # Already patched?
        if grep -qF "$ateam_cfg" "$file"; then
            echo "Already patched."
            return 0
        fi
        # Make sure stock config exists
        if ! grep -qF "$stock_cfg" "$file"; then
            echo "ERROR: Stock kernel config not found:"
            echo "  $stock_cfg"
            return 1
        fi
        > "$tmp"
        while IFS= read -r line || [[ -n "$line" ]]; do
            #
            # Single-line format:
            #
            # TARGET_KERNEL_CONFIG += vendor/ext_config/foo.config
            #
            if [[ "$line" == *"TARGET_KERNEL_CONFIG +="*"$stock_cfg"* ]]; then
                printf '%s\n' 'TARGET_KERNEL_CONFIG += \' >> "$tmp"
                printf '\t%s \\\n' "$stock_cfg" >> "$tmp"
                printf '\t%s\n' "$ateam_cfg" >> "$tmp"
                continue
            fi
            #
            # Multi-line stock config:
            #
            # TARGET_KERNEL_CONFIG += \
            #     vendor/ext_config/foo.config
            #
            if [[ "$line" == *"$stock_cfg"* ]]; then
                printf '\t%s \\\n' "$stock_cfg" >> "$tmp"
                printf '\t%s\n' "$ateam_cfg" >> "$tmp"
                continue
            fi
            printf '%s\n' "$line" >> "$tmp"
        done < "$file"
        mv "$tmp" "$file"
    }
    patch_target_kernel_config \
        "$ROM_PATH/device/motorola/${DEVICE_CODENAME}/BoardConfig.mk" \
        "vendor/ext_config/moto-parrot-mona.config" \
        "vendor/ext_config/A-Team-moto-mona.config"
    echo
    echo "1/1 ..."
    echo 
    sleep 3

    # Copy & Enable A-Team-moto-avatrn.config Kernel Config
    echo "Copying A-Team-moto-${DEVICE_CODENAME}.config Into sm7435 Kernel Tree ..."
    cp -r $A_TEAM_SETUP_LOCATION/kernel/motorola/sm7435/arch/arm64/configs/vendor/ext_config/A-Team-moto-${DEVICE_CODENAME}.config $ROM_PATH/kernel/motorola/sm7435/arch/arm64/configs/vendor/ext_config
    echo 
    echo "1/1 ..."
    echo 
    sleep 3

    # Patch lineage_mona.mk
    echo "Patching lineage_${DEVICE_CODENAME}.mk ..."
    sed -i 's/PRODUCT_BRAND := motorola/PRODUCT_BRAND := Motorola/g' $ROM_PATH/device/motorola/${DEVICE_CODENAME}/lineage_${DEVICE_CODENAME}.mk
    echo 
    echo "1/3 ..."
    echo 
    sleep 3
    sed -i 's/PRODUCT_MANUFACTURER := motorola/PRODUCT_MANUFACTURER := Motorola/g' $ROM_PATH/device/motorola/${DEVICE_CODENAME}/lineage_${DEVICE_CODENAME}.mk
    echo "2/3 ..."
    echo 
    sleep 3
    sed -i 's/PRODUCT_MODEL := motorola edge 2024/PRODUCT_MODEL := Moto Edge - 2024/g' $ROM_PATH/device/motorola/${DEVICE_CODENAME}/lineage_${DEVICE_CODENAME}.mk
    echo "3/3 ..."
    echo 
    sleep 3

    # Patch device.mk
    echo "Patching ${DEVICE_DISPLAY_CODENAME} device.mk In Device Tree ..."
    sed -i '/TARGET_SCREEN_DENSITY := 400/ a\\ \n# Disable Adaptive Brightness\nPRODUCT_PACKAGES += MonaSettingsProviderOverlay' $ROM_PATH/device/motorola/${DEVICE_CODENAME}/device.mk
    echo 
    echo "1/2..."
    echo 
    sleep 3

    # Add A-Team.mk Patch
    sed -i '/# Boot animation/i\
# A-Team ROM Addons\
$(call inherit-product, device/A-Team/A-Team.mk)\
' "$ROM_PATH/device/motorola/$DEVICE_CODENAME/device.mk" 
    echo "2/2 ..."
    echo
    sleep 3

    # Move Files To Location
    echo "Copying $DEVICE_DISPLAY_CODENAME Files Into Device Tree ..."
    cp -r $A_TEAM_SETUP_LOCATION/device/${DEVICE_CODENAME}/rro_overlays $ROM_PATH/device/motorola/${DEVICE_CODENAME}
    echo 
    echo "1/1 ..."
    echo 
    sleep 3

    echo "Device Sync & Setup Complete."
    echo

    # Patch For Dirty Kernel
    #echo "Applying Dirty Kernel Patch..."
    #echo ""
    #echo "1/2..."
    #echo ""
    #cd kernel/motorola/sm7435
    #git add .
    #sleep 3
    #echo "2/2..."
    #echo ""
    #git commit -m "tmp"
    #echo ""
    #sleep 3
    #cd ../../../

    mkdir -p "$(dirname "$MONA_SETUP_CHECK")"
    touch "$MONA_SETUP_CHECK"
fi
