#!/bin/bash

# Exit on error
set -e

echo "🚀 Starting Expo Server Setup..."

# 1. Install Node.js (v20) if missing
if ! command -v node &> /dev/null; then
    echo "📦 Installing Node.js v20..."
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
    apt-get install -y nodejs
else
    echo "✅ Node.js is already installed: $(node -v)"
fi

# 2. Update Repository (Check if it's a git repo first)
echo "🔄 Checking Repository..."
cd /var/www/html

if [ -d ".git" ]; then
    echo "🔄 Updating Project Repository..."
    git pull origin feature/gcs-migration
else
    echo "⚠️  NOTE: /var/www/html is not a Git repository. Skipping 'git pull'."
    echo "   (If you manually uploaded files, please ensure they are up to date.)"
fi

# 3. Check mobile-app directory
TARGET_DIR=""

if [ -d "mobile-app" ]; then
    TARGET_DIR="mobile-app"
elif [ -d "Antigravity/mobile-app" ]; then
    TARGET_DIR="Antigravity/mobile-app"
elif [ -d "webgruppo_new/mobile-app" ]; then
    TARGET_DIR="webgruppo_new/mobile-app"
fi

if [ -n "$TARGET_DIR" ]; then
    cd "$TARGET_DIR"
    echo "📂 Found mobile-app at: $TARGET_DIR"
else
    echo "❌ Error: 'mobile-app' directory not found in /var/www/html, /var/www/html/Antigravity, or /var/www/html/webgruppo_new!"
    echo "   Please check where you uploaded the project files."
    echo "   Current contents of /var/www/html:"
    ls -F /var/www/html
    exit 1
fi

# 4. Install Dependencies
echo "📦 Installing NPM Dependencies..."
npm install

# 5. Global Expo CLI (Optional but helpful)
echo "📦 Installing Expo CLI globally..."
npm install -g expo-cli

echo "✅ Setup Complete!"
echo ""
echo "👉 To start the server, run one of the following commands:"
echo "   - For Tunnel (recommended): npx expo start --tunnel"
echo "   - For Local IP:             npx expo start"
echo ""
echo "⚠️  Note: If using --tunnel, you may need to log in to Expo first with 'npx expo login'"
