#!/bin/bash
# Smart deployment script that checks Redis availability first
set -e  # stop on first error

cd ~/public_html

git stash

echo "▶ Pulling latest code..."
git pull origin master

echo "▶ Setting environment file..."
if [[ "master" == "master" || "master" == "tag" ]]; then
  cp .env.prod .env
  echo "  → Using .env.prod"
elif [[ "master" == "main" ]]; then
  cp .env.dev .env
  echo "  → Using .env.dev"
else
  echo "  ⚠ No env mapping found, skipping cp"
fi

echo "▶ Installing Composer dependencies..."
composer install --prefer-dist --no-progress --no-dev --optimize-autoloader

echo "▶ Checking Redis availability..."
# Check if Redis is available by reading from .env
REDIS_HOST=$(grep "^REDIS_HOST=" .env | cut -d '=' -f2)
REDIS_PORT=$(grep "^REDIS_PORT=" .env | cut -d '=' -f2)

# Default values if not found
REDIS_HOST=${REDIS_HOST:-127.0.0.1}
REDIS_PORT=${REDIS_PORT:-6379}

echo "  → Redis config: $REDIS_HOST:$REDIS_PORT"

# Function to check Redis connection
check_redis() {
  if command -v redis-cli &> /dev/null; then
    if redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" ping &> /dev/null; then
      return 0
    fi
  fi

  # Try using PHP to check Redis connection
  php -r "
  try {
    \$redis = new Redis();
    \$connected = \$redis->connect('$REDIS_HOST', $REDIS_PORT, 2);
    if (\$connected) {
      \$redis->close();
      exit(0);
    }
  } catch (Exception \$e) {
  }
  exit(1);
  " 2>/dev/null && return 0

  return 1
}

REDIS_AVAILABLE=false
if check_redis; then
  echo "  ✅ Redis is available"
  REDIS_AVAILABLE=true
else
  echo "  ⚠ Redis is NOT available - will skip cache operations"
fi

echo "▶ Running artisan commands..."

# Clear caches safely - skip cache if Redis is unavailable
echo "  → Clearing config cache..."
php artisan config:clear

echo "  → Clearing route cache..."
php artisan route:clear

echo "  → Clearing view cache..."
php artisan view:clear

echo "  → Clearing event cache..."
php artisan event:clear

echo "  → Clearing compiled cache..."
php artisan clear-compiled

# Only clear cache if Redis is available
if [ "$REDIS_AVAILABLE" = true ]; then
  echo "  → Clearing application cache..."
  php artisan cache:clear
else
  echo "  → Skipping cache clear (Redis unavailable)"
fi

# Optimize application
echo "  → Optimizing config..."
php artisan config:cache

echo "  → Optimizing routes..."
php artisan route:cache

echo "  → Optimizing views..."
php artisan view:cache

# Only optimize cache if Redis is available
if [ "$REDIS_AVAILABLE" = true ]; then
  echo "  → Optimizing application cache..."
  php artisan cache:optimize
else
  echo "  → Skipping cache optimize (Redis unavailable)"
fi

echo "✅ Deploy complete."

if [ "$REDIS_AVAILABLE" = false ]; then
  echo ""
  echo "⚠ WARNING: Redis was unavailable during deployment."
  echo "  Application will use database cache instead."
  echo "  Consider checking Redis service status."
fi