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

# Device Auto select since fogos spans 2 devices
if [[ "$DEVICE_DISPLAY_NAME" == "Moto G34 5G" ]]; then
    sed -i 's/PRODUCT_MODEL := moto g34 5G/PRODUCT_MODEL := Moto G34 5G/g' $ROM_PATH/device/motorola/${DEVICE_CODENAME}/lineage_${DEVICE_CODENAME}.mk
    echo "3/3 ..."
    echo 
    sleep 3
elif [[ "$DEVICE_DISPLAY_NAME" == "Moto G45 5G" ]]; then
    sed -i 's/PRODUCT_MODEL := moto g34 5G/PRODUCT_MODEL := Moto G45 5G/g' $ROM_PATH/device/motorola/${DEVICE_CODENAME}/lineage_${DEVICE_CODENAME}.mk
    echo "3/3 ..."
    echo 
    sleep 3
# Device Auto select since rtwo spans 3 devices
elif [[ "$DEVICE_DISPLAY_NAME" == "Moto Edge 40 Pro" ]]; then
    sed -i 's/PRODUCT_MODEL := motorola edge 40 pro/PRODUCT_MODEL := Moto Edge 40 Pro/g' $ROM_PATH/device/motorola/${DEVICE_CODENAME}/lineage_${DEVICE_CODENAME}.mk
    echo "3/3 ..."
    echo 
    sleep 3
elif [[ "$DEVICE_DISPLAY_NAME" == "Moto X40" ]]; then
    sed -i 's/PRODUCT_MODEL := motorola edge 40 pro/PRODUCT_MODEL := Moto X40/g' $ROM_PATH/device/motorola/${DEVICE_CODENAME}/lineage_${DEVICE_CODENAME}.mk
    echo "3/3 ..."
    echo 
    sleep 3
elif [[ "$DEVICE_DISPLAY_NAME" == "Moto Edge+ 2023" ]]; then
    sed -i 's/PRODUCT_MODEL := motorola edge 40 pro/PRODUCT_MODEL := Moto Edge+ - 2023/g' $ROM_PATH/device/motorola/${DEVICE_CODENAME}/lineage_${DEVICE_CODENAME}.mk
    echo "3/3 ..."
    echo 
    sleep 3
fi

# Download Legacy Kernel-SU apk
download_legacy_ksu() {
    # Ensure LEGACY_KSU_VERSION is set
    if [ -z "$LEGACY_KSU_VERSION" ]; then
        echo ""
        echo "LEGACY_KSU_VERSION Is Not Set. Please Specify The Legacy KSU Version"
        return 1
    fi

    # GitHub API URL for the specified release version
    API_URL="https://api.github.com/repos/tiann/KernelSU/releases/tags/$LEGACY_KSU_VERSION"

    # Fetch the specified release info using GitHub API
    RELEASE_INFO=$(curl -s "$API_URL")

    # Check if the release info is valid
    if echo "$RELEASE_INFO" | jq -e .message >/dev/null 2>&1; then
        echo ""
        echo "Error Fetching Release Information: $(echo "$RELEASE_INFO" | jq -r .message)"
        return 1
    fi

    # Extract the URL of the .apk file for the specified version using jq
    APK_URL=$(echo "$RELEASE_INFO" | jq -r '.assets[] | select(.name | test("KernelSU_v[0-9._-]+release\\.apk$")) | .browser_download_url')

    # Check if an APK URL was found
    if [ -n "$APK_URL" ]; then
        # Extract filename from URL
        FILENAME=$(basename "$APK_URL")
    
        # Download the .apk file
        curl -L -o "out/target/product/$DEVICE_CODENAME/system/A-Team/Apps/KSU.apk" "$APK_URL"
    
        # Echo the filename downloaded
        echo ""
        echo "Specific Version Release FileName:  $FILENAME"
    else
        echo "No .apk File Found For Version $LEGACY_KSU_VERSION"
        echo ""
        echo "Do You Have Internet & Correct KSU Version ?"
        echo ""
        echo "Exiting, Please Try Again !!"
        sleep 20
        exit
    fi
}

# Download Newest Kernel-SU apk
download_newest_ksu() {
    # GitHub API URL for the latest release
    API_URL="https://api.github.com/repos/tiann/KernelSU/releases/latest"

    # Fetch the latest release info using GitHub API
    RELEASE_INFO=$(curl -s "$API_URL")

    # Extract the URL of the latest .apk file using jq
    APK_URL=$(echo "$RELEASE_INFO" | jq -r '.assets[] | select(.name | test("KernelSU_v[0-9._-]+release\\.apk$")) | .browser_download_url')

    # Check if an APK URL was found
    if [ -n "$APK_URL" ]; then
        # Extract filename from URL
        FILENAME=$(basename "$APK_URL")
    
        # Download the .apk file
        curl -L -o "out/target/product/$DEVICE_CODENAME/system/A-Team/Apps/KSU.apk" "$APK_URL"
    
        # Echo the filename downloaded
        echo ""
        echo "Latest Release FileName:  $FILENAME"
    else
        echo ""
        echo "No .apk File Found In The Latest Release."
    fi
}

# Build Kernel-SU Boot Image
build_ksu() {
    cd ../../../../

    if [[ $DEVICE_CODENAME == milanf ]]
    then
    # Copy Milanf Kernel & Enable Kernel-SU
    echo "Copying Kernel For Kernel-SU..."
    echo ""
    echo "1/1..."
    cp -r kernel/motorola/msm-5.4 kernel/motorola/msm-5.4-Standard
    cd kernel/motorola/msm-5.4
    sed -i 's/CONFIG_KSU=n/CONFIG_KSU=y/g' arch/arm64/configs/vendor/milanf_defconfig
    #sed -i 's/CONFIG_LOCALVERSION="-PizzaG_x64"/CONFIG_LOCALVERSION="-PizzaG_x64-KSU"/g' arch/arm64/configs/vendor/milanf_defconfig
    git add .
    sleep 5
    echo ""
    git commit -m "tmp"
    echo ""
    # Patch Kernel For Kernel-SU
    echo "Patching Kernel For Kernel-SU..."
    echo ""
    curl -LSs "https://raw.githubusercontent.com/tiann/KernelSU/main/kernel/setup.sh" | bash -s $LEGACY_KSU_VERSION
    cd ../../../

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

    # Set Build Environment
    echo "Setting Build Environment..."
    echo ""
    . build/envsetup.sh
    sleep 3

    # Lunch Command Auto Selector
    lunch_command
    if [[ $ROM_BUILD_TYPE == VANILLA ]]
    then
    export WITH_GMS=false
    fi

    # Build Kernel-SU Boot Image
    $KSU_BUILD_COMMAND 

    # Sanity Check & Move Built Boot Image
    if [[ -f $OUT/boot.img ]]
    then
    cp -r $OUT/boot.img $OUT/A-Team/KSU.img
    echo ""
    echo "Cleaning Up..."
    echo ""
    rm -rf kernel/motorola/msm-5.4
    mv kernel/motorola/msm-5.4-Standard kernel/motorola/msm-5.4
    echo "Boot Image Stuff Done"
    echo ""
    # Patch For Dirty Kernel
    echo "Applying Dirty Kernel Patch..."
    echo ""
    echo "1/2..."
    echo ""
    cd kernel/motorola/msm-5.4
    git add .
    sleep 3
    echo "2/2..."
    echo ""
    git commit -m "tmp"
    echo ""
    sleep 3
    cd ../../../
    else
    echo ""
    echo ""
    echo "Building Boot Image Failed, Please Try Again"
    echo ""
    echo "Cleaning Up..."
    echo ""
    rm -rf kernel/motorola/msm-5.4
    mv kernel/motorola/msm-5.4-Standard kernel/motorola/msm-5.4
    echo ""
    # Patch For Dirty Kernel
    echo "Applying Dirty Kernel Patch..."
    echo ""
    echo "1/2..."
    echo ""
    cd kernel/motorola/msm-5.4
    git add .
    sleep 3
    echo "2/2..."
    echo ""
    git commit -m "tmp"
    echo ""
    sleep 3
    cd ../../../
    echo "PRESS ENTER TO EXIT"
    read
    clear
    exec "$BASH" "$0" "$@"
    fi
    fi

    if [[ $DEVICE_CODENAME == yume ]]
    then
    # Copy Yume Kernel & Enable Kernel-SU
    echo "Copying Kernel For Kernel-SU..."
    echo ""
    echo "1/1..."
    echo ""
    cp -r kernel/motorola/msm-5.10 kernel/motorola/msm-5.10-Standard
    cd kernel/motorola/msm-5.10
    sed -i 's/CONFIG_KSU=n/CONFIG_KSU=y/g' arch/arm64/configs/vendor/yume_defconfig
    #sed -i 's/CONFIG_LOCALVERSION="-PizzaG_x64_GKI"/CONFIG_LOCALVERSION="-PizzaG_x64_GKI-KSU"/g' arch/arm64/configs/vendor/yume_defconfig
    git add .
    sleep 5
    echo ""
    git commit -m "tmp"
    echo ""
    # Patch Kernel For Kernel-SU
    echo "Patching Kernel For Kernel-SU..."
    echo ""
    curl -LSs "https://raw.githubusercontent.com/tiann/KernelSU/main/kernel/setup.sh" | bash -
    cd ../../../

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

    # Set Build Environment
    echo "Setting Build Environment..."
    echo ""
    . build/envsetup.sh
    sleep 3

    # Lunch Command Auto Selector
    lunch_command
    if [[ $ROM_BUILD_TYPE == VANILLA ]]
    then
    export WITH_GMS=false
    fi

    # Build Kernel-SU Boot Image
    $KSU_BUILD_COMMAND 

    # Sanity Check & Move Built Boot Image
    if [[ -f $OUT/boot.img ]]
    then
    mv $OUT/boot.img $OUT/A-Team/KSU.img >/dev/null 2>&1
    echo ""
    echo "Cleaning Up..."
    echo ""
    rm -rf kernel/motorola/msm-5.10
    mv kernel/motorola/msm-5.10-Standard kernel/motorola/msm-5.10
    echo "Boot Image Stuff Done"
    echo ""
    # Patch For Dirty Kernel
    echo "Applying Dirty Kernel Patch..."
    echo ""
    echo "1/2..."
    echo ""
    cd kernel/motorola/msm-5.10
    git add .
    sleep 3
    echo "2/2..."
    echo ""
    git commit -m "tmp"
    echo ""
    sleep 3
    cd ../../../
    else
    echo ""
    echo ""
    echo "Building Boot Image Failed, Please Try Again"
    echo ""
    echo "Cleaning Up..."
    echo ""
    rm -rf kernel/motorola/msm-5.10
    mv kernel/motorola/msm-5.10-Standard kernel/motorola/msm-5.10
    echo ""
    # Patch For Dirty Kernel
    echo "Applying Dirty Kernel Patch..."
    echo ""
    echo "1/2..."
    echo ""
    cd kernel/motorola/msm-5.10
    git add .
    sleep 3
    echo "2/2..."
    echo ""
    git commit -m "tmp"
    echo ""
    sleep 3
    cd ../../../
    echo "PRESS ENTER TO EXIT"
    read
    clear
    exec "$BASH" "$0" "$@"
    fi

    fi
}

# Installer - Custom
installer_custom() {
    echo -e "\nExporting A-Team Custom Build Variables For Rom..."
    echo ""

    # Copy A-Team Custom ChangeLog If Found
    if [ -f A-Team_Changelog/Changelog.txt.$DEVICE_NAME ]; then
    echo "Copying Custom Changelog To Rom..."
    echo "" 
    cp -r A-Team_Changelog/Changelog.txt.$DEVICE_NAME out/target/product/$DEVICE_CODENAME/Changelog.txt
    cp -r A-Team_Changelog/Changelog.txt.$DEVICE_NAME out/target/product/$DEVICE_CODENAME/system/etc/Changelog.txt
    cp -r A-Team_Changelog/Changelog.txt.$DEVICE_NAME Changelog.txt
    fi

    # Copy A-Team Additions
    echo "Copying A-Team Additions To Rom..."
    echo ""
    cp -r device/$DT_MANUFACTURER/A-Team/A-Team out/target/product/$DEVICE_CODENAME/system

    # Auto Select Mechanism To Download Newest KSU apk or Legacy KSU apk
    if [[ $LEGACY_KSU == false ]] 
    then
    # Download Newest Kernel-SU APK
    download_newest_ksu
    echo ""

    elif [[ $LEGACY_KSU == true ]] 
    then
    # Download Specific Kernel-SU APK
    download_legacy_ksu
    echo ""
    fi   

    # Copy A-Team Apps
    #echo "Copying A-Team Apps To Rom..."
    #echo ""
    #cp -r device/$DT_MANUFACTURER/A-Team/Apps/TimeWeather out/target/product/$DEVICE_CODENAME/product/app/TimeWeather
    #echo "Building Rom With A-Team Custom Installer..."
    #echo ""

    # Set Build Environment
    echo "Setting Build Environment..."
    echo ""
    . build/envsetup.sh
    sleep 3

    # Lunch Command Auto Selector
    lunch_command
    if [[ $ROM_BUILD_TYPE == VANILLA ]]
    then
    export WITH_GMS=false
    fi

    # Build Rom
    $CUSTOM_INSTALLER_BUILD_COMMAND
    echo ""
    echo ""
    echo "PRESS ENTER TO CONTINUE"
    read
    clear

    # A-Team Sanity Check For Custom Installer Rom Completion    
    if [[ $ROM_VENDOR_NAME == cherish ]]
        then
        zip $OUT/IMAGES.zip $OUT/obj/PACKAGING/target_files_intermediates/cherish_$DEVICE_CODENAME-target_files/IMAGES/*.img
        unzip -j $OUT/IMAGES.zip -d $OUT/A-Team
        clear
        rom_sanity_finalize
    elif [ -f $OUT/$ROM_DEFAULT_ZIP_NAME ]; then
       clear
       rom_sanity_finalize
    else
       echo ""
       echo "It Doesn't Look Like The Build Completed😱"
       echo "Cannot Find Finished Rom"
       echo "Better Luck Next Time"
       echo "Please Try Again!"
       echo ""
       echo ""
       echo "PRESS ENTER TO EXIT"
       read
       #echo "PRESS ENTER TO RELOAD BUILD MENU"
       #read
       clear
       # Remove Uneeded Changelog.txt
       #cd ../../../../
       #rm -rf Changelog.txt
       exit 0
       #exec "$BASH" "$0" "$@"
    fi
}

# Inject Recovery Into Needed Boot Images
inject_recovery() {
    echo -e "\nInjecting Recovery Ramdisk Into Boot Images...\n"
    echo "$SUDO_PASS" | sudo -S rm -rf Patch-TMP/*

    # Change to the directory where the script is located
    cd "$(dirname "$0")"

    # Ensure the current working directory is now the script's location
    echo "Current Working Directory: $(pwd)"
    echo ""

    cp -r device/$DT_MANUFACTURER/A-Team/Final_Zip/AIK/* $OUT/Patch-TMP >/dev/null 2>&1

    # Define Arrays For boot - KSU - Magisk & Recovery Images
    boot_images=("OFRP" "TWRP")
    recovery_images=("OFRP" "TWRP")
    
    # Loop Through & Copy Recovery Images
    for recovery in "${recovery_images[@]}"; do

        # Copy Recovery Images To AIK Ramdisk Folders
        echo -e "Copying ${recovery}-R.img ==> ${recovery}-R...\n"
        cp -r device/$DT_MANUFACTURER/A-Team/Final_Zip/Devices/$DEVICE_NAME/${recovery}-R.img $OUT/Patch-TMP/${recovery}-R 
        sleep 2

        echo -e "Copying ${recovery}-R.img ==> KSU/${recovery}-R...\n"
        cp -r device/$DT_MANUFACTURER/A-Team/Final_Zip/Devices/$DEVICE_NAME/${recovery}-R.img $OUT/Patch-TMP/KSU/${recovery}-R
        sleep 2
    done

    # Change to the OUT directory 
    cd $OUT

    # Ensure the current working directory is now the script's location
    echo "Current Working Directory: $(pwd)"

    # Loop Through & Process Image Injection
    for boot in "${boot_images[@]}"; do

    ################################
    # Process Unrooted Boot Images #
###############################################################################################

        # Remove Prior Images
        echo -e "Removing Prior Image in ${boot}...\n"
        rm -rf Patch-TMP/$boot/*.img
        sleep 2

        # Copy boot.img Images
        echo -e "Copying boot.img ==> ${boot}...\n"
        cp -r A-Team/boot.img Patch-TMP/$boot
        sleep 2

        # Extract boot.img Images
        echo -e "Extracting boot.img ==> ${boot}...\n"
        echo "$SUDO_PASS" | sudo -S bash -c "./Patch-TMP/${boot}/unpackimg.sh"
        sleep 2

        # Delete Extracted boot.img Ramdisk Folders
        echo -e "Deleting Extracted Ramdisk Folder ==> ${boot}...\n"
        echo "$SUDO_PASS" | sudo -S rm -rf Patch-TMP/${boot}/ramdisk
        sleep 2

        # Extract Recovery Ramdisks
        echo -e "Extracting Recovery Ramdisk Folder ==> ${boot}-R...\n"
        echo "$SUDO_PASS" | sudo -S bash -c "./Patch-TMP/${boot}-R/unpackimg.sh"
        sleep 2

        # Copy Recovery Ramdisk To Extracted Boot Image
        echo -e "Copying Recovery Ramdisk: ${boot}-R To Extracted Boot Image ==> ${boot}...\n"
        echo "$SUDO_PASS" | sudo -S cp -r Patch-TMP/${boot}-R/ramdisk Patch-TMP/$boot
        sleep 2

        # Rebuild Boot Images With Recovery Ramdisk
        echo -e "Rebuilding Boot Image With Recovery Ramdisk ==> ${boot}...\n"
        echo "$SUDO_PASS" | sudo -S bash -c "./Patch-TMP/${boot}/repackimg.sh"
        sleep 2

        # Copy Rebuilt Images To Final Location
        echo -e "Copying Rebuilt: ${boot} Image ==> Boot-${boot}.img...\n"
        cp -r Patch-TMP/${boot}/image-new.img A-Team/Boot-${boot}.img
        sleep 2
###############################################################################################


    ##############################
    # Process Magisk Boot Images #
###############################################################################################

        # Copy Image For Injection With Magisk
        echo -e "Copying Rebuilt: ${boot} Image ==> Magisk Patcher...\n"
        cp -r Patch-TMP/${boot}/image-new.img Patch-TMP/Patcher/boot.img
        sleep 2

        # Patch Image With Magisk
        echo -e "Patching ${boot} Image With Magisk Root...\n"
        sh Patch-TMP/Patcher/boot_patch.sh boot.img
        sleep 2

        # Cleanup
        echo -e "Cleaning Up...\n"
        rm -rf Patch-TMP/Patcher/kernel_dtb
        rm -rf Patch-TMP/Patcher/ramdisk.cpio
        rm -rf Patch-TMP/Patcher/stock_boot.img
        sleep 2

        # Move Patched Boot Image
        echo -e "Moving Magisk Patched Boot Image: Magisk-${boot}.img...\n"
        mv Patch-TMP/Patcher/new-boot.img A-Team/Magisk-${boot}.img
        sleep 2
        #mv Patch-TMP/Patcher/Magisk_Patched_Boot.img A-Team/Magisk-${boot}.img
###############################################################################################


    ###########################
    # Process KSU Boot Images #
###############################################################################################

        echo -e "\nCopying & Patching KSU Boot Image With Recovery Ramdisk...\n"        
        # Copy KSU Boot Image
        echo -e "Copying KSU Boot Image ==> KSU/${boot}...\n"
        cp -r A-Team/KSU.img Patch-TMP/KSU/${boot}
        sleep 2

        # Extract KSU Boot Image
        echo -e "Extracting KSU Boot Image In: KSU/${boot}...\n"
        echo "$SUDO_PASS" | sudo -S bash -c "./Patch-TMP/KSU/${boot}/unpackimg.sh"
        sleep 2

        # Delete Extracted Boot Image Ramdisk
        echo -e "Deleting KSU Extracted Ramdisk In: KSU/${boot}...\n"
        echo "$SUDO_PASS" | sudo -S rm -rf Patch-TMP/KSU/${boot}/ramdisk
        sleep 2

        # Extract Recovery Ramdisks
        echo -e "Extracting Recovery Ramdisk In: KSU/${boot}-R...\n"
        echo "$SUDO_PASS" | sudo -S bash -c "./Patch-TMP/KSU/${boot}-R/unpackimg.sh"
        sleep 2

       # Copy Extracted Recovery Ramdisk To Extracted Boot Image
        echo -e "Copying Extracted Recovery Ramdisk In: KSU/${boot}-R ==> KSU/${boot}...\n"
        echo "$SUDO_PASS" | sudo -S cp -r Patch-TMP/KSU/${boot}-R/ramdisk Patch-TMP/KSU/${boot}
        sleep 2

        # Rebuild KSU Boot Images With Recovery Ramdisk
        echo -e "Rebuilding KSU Boot Image With Recovery Ramdisk: KSU/${boot}...\n"
        echo "$SUDO_PASS" | sudo -S bash -c "./Patch-TMP/KSU/${boot}/repackimg.sh"
        sleep 2

        # Move Rebuilt Images To Final Location
        echo -e "Copying Rebuilt KSU Boot Image: KSU-${boot}.img...\n"
        cp -r Patch-TMP/KSU/${boot}/image-new.img A-Team/KSU-${boot}.img
        sleep 2
    done
###############################################################################################

    # Cleanup
    echo -e "Cleaning Up...\n"
    echo "$SUDO_PASS" | sudo -S rm -rf Patch-TMP/*
}

# Magisk Patch Boot Image
magisk_patch() {
    # Magisk Patch Boot Image & Place Into Location
    if [[ $A_TEAM_MAGISK == true ]]
    then
    echo ""
    echo "Magisk Patching Boot Image..."
    echo ""
    cd Magisk_Boot_Patcher
    ./Magisk_Boot_Patcher.sh
    cd ../
    echo ""
    # A-Team Sanity Check For Magisk Patched Boot Image
    if [ -f $OUT/Magisk.img ]; then
       echo "-Magisk Patched Boot Sanity Check-"
       echo ""
       echo "Magisk Patched Boot Image Found😁"
       echo ""
       echo "Moving Magisk Patched Boot Image To Location..."
       mv Magisk.img A-Team
    else
       echo "-Magisk Patched Boot Sanity Check-"
       echo ""
       echo "Magisk Patched Boot Image NOT Found😱"
       echo "Please Try Again!"
       echo ""
       echo ""
       echo "PRESS ENTER TO EXIT"
       read
       exit 1
    fi

    fi       
}

rom_sanity_finalize() {
    echo ""
    echo "-Rom Sanity Check-"
    echo ""
    echo "It Looks Like The Rom Build Finished😁"
    echo "Found Finished Rom"
    echo "Fantastic Job!!"
    echo ""
    echo ""
    echo "PRESS ENTER TO CONTINUE"
    read
    clear

    # Pre-Finalize
    echo ""
    echo "Now Lets Tidy Up & Repackage The Rom Into Its Final Packaging..."
    echo ""
    echo "Moving Files..."
    echo ""

    # List of common files to copy directly to OUT
    common_files=("A-Team" "Magisk_Boot_Patcher")
    # List of device-specific files to copy directly to OUT
    device_files=("A-Team_Rom_Flasher-LINUX.sh" "A-Team_Rom_Flasher-WINDOWS.bat" "META-INF")
    # List of images to copy to OUT/A-Team, suppressing errors for non-existent files
    images=("OFRP.img" "TWRP.img")
    # List of other device-specific files to copy to OUT/A-Team
    other_files=("systemrw_1.32-Encrypt" "systemrw_1.32-NoEncrypt" "myargs.txt" "LINUX.sh" "WINDOWS.bat")
    # Copy common files
    for file in "${common_files[@]}"; do
        cp -r "device/$DT_MANUFACTURER/A-Team/Final_Zip/$file" "$OUT"
    done
    # Copy device-specific files
    for file in "${device_files[@]}"; do
        cp -r "device/$DT_MANUFACTURER/A-Team/Final_Zip/Devices/$DEVICE_NAME/$file" "$OUT"
    done
    # Copy images to OUT/A-Team, suppressing errors for non-existent files
    for img in "${images[@]}"; do
        cp -r "device/$DT_MANUFACTURER/A-Team/Final_Zip/Devices/$DEVICE_NAME/$img" "$OUT/A-Team" >/dev/null 2>&1
    done
    # Copy other device-specific files to OUT/A-Team
    for file in "${other_files[@]}"; do
        cp -r "device/$DT_MANUFACTURER/A-Team/Final_Zip/Devices/$DEVICE_NAME/$file" "$OUT/A-Team"
    done

    echo "Extracting Rom To Repackage Into Custom Installer..."
    echo ""
    cd $OUT
    unzip -o $ROM_DEFAULT_ZIP_NAME
    echo ""

    # Magisk Patch Boot Image & Place Into Location
    magisk_patch

    # Move Images Into Place For Packing
    echo ""
    echo "Moving Built Partition Images To Location..."
    echo ""

    # List of images to move
    images=("boot.img" "dtbo.img" "product.img" "super_empty.img" "system.img" "vbmeta.img" "vendor.img" "recovery.img" "system_ext.img" "vbmeta_system.img" "vendor_boot.img" "vendor_dlkm.img")

    # Move each image to the A-Team directory, suppressing errors for non-existent files
    for img in "${images[@]}"; do
        mv "$img" A-Team >/dev/null 2>&1
    done
    sleep 3

    # Build KSU Boot Image
    build_ksu

    # Inject Recovery If Device Recovery In Boot
    if [[ $INJECT_RECOVERY == true ]] 
    then
    cd $OUT
    inject_recovery
    fi   

    # Build Encryption Disabled Vendor
    cd "$(dirname "$(readlink -f "$0")")"
    build_patched_vendor
    cd $OUT

    # Final Packaging
    echo "Applying Final Rom Package Naming..."
    echo ""
    if [ $DEVICE_CODENAME == amogus ]; then

   # Zip Naming - Gapps
       if [[ $GAPPS == true ]] 
       then
       export ROM_NAME="$ROM_ZIP_NAME-$MAJOR_VERSION.$MINOR_VERSION-UNOFFICIAL-GAPPS-$DEVICE_CODENAME-v$INTERNAL_VERSION"
       # Zip Naming - MicroG
       elif [[ $MICROG == true ]] 
       then
       export ROM_NAME="$ROM_ZIP_NAME-$MAJOR_VERSION.$MINOR_VERSION-UNOFFICIAL-MICROG-$DEVICE_CODENAME-v$INTERNAL_VERSION"
       # Zip Naming - Vanilla
       elif [[ $GAPPS == false ]] 
       then
       export ROM_NAME="$ROM_ZIP_NAME-$MAJOR_VERSION.$MINOR_VERSION-UNOFFICIAL-VANILLA-$DEVICE_CODENAME-v$INTERNAL_VERSION"
       fi       
    else
       # Zip Naming - Gapps
       if [[ $GAPPS == true ]] 
       then
       export ROM_NAME="$ROM_ZIP_NAME-$MAJOR_VERSION.$MINOR_VERSION-UNOFFICIAL-GAPPS-$DEVICE_CODENAME-$MODEL_NUMBER-v$INTERNAL_VERSION"
       # Zip Naming - MicroG
       elif [[ $MICROG == true ]] 
       then
       export ROM_NAME="$ROM_ZIP_NAME-$MAJOR_VERSION.$MINOR_VERSION-UNOFFICIAL-MICROG-$DEVICE_CODENAME-$MODEL_NUMBER-v$INTERNAL_VERSION"
       # Zip Naming - Vanilla
       elif [[ $GAPPS == false ]] 
       then
       export ROM_NAME="$ROM_ZIP_NAME-$MAJOR_VERSION.$MINOR_VERSION-UNOFFICIAL-VANILLA-$DEVICE_CODENAME-$MODEL_NUMBER-v$INTERNAL_VERSION"
       fi  
    fi
    echo "Compressing Final Zip Rom Package..."
    echo ""
    echo ""
    zip -r $ROM_NAME.zip "META-INF" "A-Team" A-Team_Rom_Flasher-LINUX.sh A-Team_Rom_Flasher-WINDOWS.bat
    echo ""
    echo ""
    echo "Checking If Final Rom Location Exists..."
    echo ""
    if [[ -d $FINAL_ROM_LOCATION/$DEVICE_NAME ]] 
    then
    echo "Found Final Rom Location..."
    else
    echo "Final Rom Location Not Found, Creating Directories..."
    echo ""
    echo ""
    mkdir $FINAL_ROM_LOCATION >/dev/null 2>&1
    mkdir $FINAL_ROM_LOCATION/$DEVICE_NAME >/dev/null 2>&1
    echo "Final Rom Location: $FINAL_ROM_LOCATION"
    fi   
    echo ""
    echo ""
    echo ""
    echo "Moving Completed Rom To: $FINAL_ROM_LOCATION/$DEVICE_NAME/$ROM_NAME.zip"
    echo ""
    echo ""
    mv $OUT/$ROM_NAME.zip $FINAL_ROM_LOCATION/$DEVICE_NAME/$ROM_NAME.zip
    echo ""
    UPLOAD=TRUE
    echo "PRESS ENTER TO CONTINUE"
    read
    # Remove Uneeded Changelog.txt
    cd ../../../../
    rm -rf Changelog.txt
    clear
    menu_upload
}


