#!/bin/bash
set -euo pipefail

# Check ENVFILE variable
if [ -z "$ENVFILE" ]; then
  echo "❌ ENVFILE variable is not set."
  exit 1
fi

# Check if the environment file exists
if [[ ! -f "$ENVFILE" ]]; then
  echo "❌ Environment file "$ENVFILE" not found."
  exit 1
fi

  # Load environment variables from ENVFILE
  if jq -e . >/dev/null 2>&1 < "$ENVFILE"; then
    echo "Parsing JSON in $ENVFILE"
    # Merge .secure and .public keys and export them
    eval "$(jq -r '.secure + .public | to_entries | .[] | @sh "export \(.key)=\(.value)"' "$ENVFILE")"
  else
    echo "Parsing key=value pairs in $ENVFILE"
    # Read key=value pairs, skip empty lines and comments
    while IFS='=' read -r key val; do
      # Skip comments and empty lines
      if [[ $key != \#* && -n "$key" ]]; then
        echo "export $key=$val"
        export "$key"="$val"
      fi
    done < "$ENVFILE"
  fi

echo "✅ Environment variables loaded successfully."

echo "📦 Starting OTA bundle process for \"${APP_NAME}\" android platform..."

# Define paths
PROJECT_NAME="\"${APP_NAME}\" Android"
ENV_FILE=$ENVFILE
PROJECT_ROOT_DIRECTORY="$(pwd)"
BUNDLE_DIR=$PROJECT_ROOT_DIRECTORY/android/output
ASSETS_DIRECTORY=$BUNDLE_DIR
JS_BUNDLE=$BUNDLE_DIR/index.android.bundle
BUNDLE_ZIP_FILE=$PROJECT_ROOT_DIRECTORY/android/index.android.bundle.zip
SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

echo "📦 Starting OTA bundle process for $PROJECT_NAME picking environment file from $ENV_FILE"

# Step 1: Create output folder
echo "🧹 Cleaning up old bundle output..."
rm -rf $BUNDLE_DIR
mkdir -p $BUNDLE_DIR $ASSETS_DIRECTORY


echo "📁 Output directory ready: $BUNDLE_DIR"

# Step 2: Bundle JS for Android using environment variables

echo "🔐 Checking ENV_KEY_NAME: $ENV_KEY"

# Bundle command base
bundle_cmd=(
  npx react-native bundle
  --platform android
  --dev false
  --entry-file index.js
  --bundle-output "$JS_BUNDLE"
  --assets-dest "$ASSETS_DIRECTORY"
)

# Check if KEYSFILE is set and not empty
if [ -n "$ENV_KEY" ]; then
  echo "🔧 Bundling JS with injected env: $ENV_KEY=$ENV_FILE"
  # Export or use the KEYSFILE variable if needed
  env "$ENV_KEY=$ENV_FILE" "${bundle_cmd[@]}"
else
  echo "🔧 Bundling JS without injected env var. Skipping injection ..."
  "${bundle_cmd[@]}"
fi

echo "📦 JS bundle and assets are generated."

# Step 3: Zip the bundle and assets
echo "📦 Creating zip files..."
cd android
find output -type f | zip index.android.bundle.zip -@
cd ..

echo "🗜️ Zip files created: $BUNDLE_ZIP_FILE"
echo "📁 ZIP structure:"
unzip -l $BUNDLE_ZIP_FILE

# Step 4: Run OTA config update
echo "⚙️ Running OTA config update... with key: ${OTA_KEY_ANDROID} on version ${V_NAME}"
node $SCRIPT_DIR/../react-native-code-sync/src/code-sync/UploadeBundleFile.js apiurl=${CODE_SYNC_BASE_URL}${UPLOAD_BUNDLE} project_key=${OTA_KEY_ANDROID} platform=android version=${V_NAME} \"message=test upload\"

#Remove zipfile
echo "🧹 Cleaning up zip and output files..."
echo "now deleting Bundle directory ${BUNDLE_DIR}"
echo "now deleting Bundle zip file ${BUNDLE_ZIP_FILE}"
rm -rf $BUNDLE_DIR $BUNDLE_ZIP_FILE

echo "✅ OTA bundle created and config updated successfully for ${PROJECT_NAME} picked environment file from ${ENV_FILE}"