#!/bin/sh

FRAMEWORK_FOLDER="Frameworks"

function execute() {

    clean
    
    download
}

function clean() {

    if [ -e $FRAMEWORK_FOLDER ]; then
        rm -r $FRAMEWORK_FOLDER && mkdir $FRAMEWORK_FOLDER
    else
        mkdir $FRAMEWORK_FOLDER
    fi
}

function download() {

    local pgw_sdk_version="PGW_SDK_iOS_v4.7.1"
    local pgw_sdk_helper_version="PGW_SDK_HELPER_iOS_v4.2.1"
    local pgw_ui_sdk_version="PGW_UI_SDK_iOS_v4.0.4"

    local frameworks=(
        "https://d27uu9vmlo4gwh.cloudfront.net/$pgw_sdk_version/$pgw_sdk_version.zip" 
        "https://d27uu9vmlo4gwh.cloudfront.net/$pgw_sdk_helper_version/$pgw_sdk_helper_version.zip" 
        "https://d27uu9vmlo4gwh.cloudfront.net/PGW_SDK_HELPER_iOS_v4.2.0/Dependencies/ZaloPay/zpdk.xcframework.zip"
        "https://d27uu9vmlo4gwh.cloudfront.net/$pgw_ui_sdk_version/App.xcframework.zip" 
        "https://d27uu9vmlo4gwh.cloudfront.net/$pgw_ui_sdk_version/Flutter.xcframework.zip" 
        "https://d27uu9vmlo4gwh.cloudfront.net/$pgw_ui_sdk_version/FlutterPluginRegistrant.xcframework.zip" 
        "https://d27uu9vmlo4gwh.cloudfront.net/$pgw_ui_sdk_version/image_gallery_saver.xcframework.zip" 
        "https://d27uu9vmlo4gwh.cloudfront.net/$pgw_ui_sdk_version/path_provider_foundation.xcframework.zip" 
        "https://d27uu9vmlo4gwh.cloudfront.net/$pgw_ui_sdk_version/pgw_sdk.xcframework.zip" 
        "https://d27uu9vmlo4gwh.cloudfront.net/$pgw_ui_sdk_version/webview_flutter_wkwebview.xcframework.zip" 
    )

    cd $FRAMEWORK_FOLDER

    for framework in "${frameworks[@]}"
    do
        
        echo "\n[PGW SDK] url: $framework"
        curl $framework > framework.zip
        unzip -q framework.zip
        rm framework.zip
    done

    if [ -e "__MACOSX" ]; then
        rm -r "__MACOSX"
    fi

    local downloaded=$(find . -name "*.xcframework" | wc -l)
    local total_of_list=$(echo "${#frameworks[@]}")

    if [ "$downloaded" -eq "$total_of_list" ]; then
        echo "[PGW SDK] download completed, please go to ios folder and run cmd: \n\n - New architecture: RCT_NEW_ARCH_ENABLED=1 bundle exec pod install \n - Old architecture: bundle exec pod install"
    else
        echo "[PGW SDK] download incomplete, please go $FRAMEWORK_FOLDER folder check the xcframework files and re-run cmd: npm explore @2c2p/pgw-sdk-react-native -- npm run ios-frameworks"
    fi
}

execute
