#!/bin/bash
export ANDROID_HOME=$HOME/android
export ANDROID_SDK_ROOT=$ANDROID_HOME
export PATH=$ANDROID_HOME/emulator:$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$PATH

set -e  # stop on error

echo "🚧 Starting APK build..."

# Step 1: Ensure native android folder exists
if [ ! -d "android" ]; then
  echo "📦 Running Expo prebuild..."
  npx expo prebuild
fi

# Step 2: Go to android folder
cd android

# Step 3: Check if keystore exists
KEYSTORE_FILE="app/my-release-key.keystore"

if [ ! -f "$KEYSTORE_FILE" ]; then
  echo "🔑 Generating keystore..."

  keytool -genkeypair -v \
    -storetype PKCS12 \
    -keystore $KEYSTORE_FILE \
    -alias my-key-alias \
    -keyalg RSA \
    -keysize 2048 \
    -validity 10000 \
    -storepass password \
    -keypass password \
    -dname "CN=Your Name, OU=Dev, O=MyApp, L=City, S=State, C=US"
fi

# Step 4: Ensure gradle.properties has signing config
GRADLE_PROPS="gradle.properties"

if ! grep -q "MYAPP_UPLOAD_STORE_FILE" $GRADLE_PROPS; then
  echo "⚙️ Adding signing config..."

  cat <<EOF >> $GRADLE_PROPS
MYAPP_UPLOAD_STORE_FILE=my-release-key.keystore
MYAPP_UPLOAD_KEY_ALIAS=my-key-alias
MYAPP_UPLOAD_STORE_PASSWORD=password
MYAPP_UPLOAD_KEY_PASSWORD=password
EOF
fi

# Step 5: Build release APK
echo "🏗️ Building APK..."
./gradlew assembleRelease

# Step 6: Output path
APK_PATH="app/build/outputs/apk/release/app-release.apk"

echo "✅ Build complete!"
echo "📦 APK located at: android/$APK_PATH"