#!/bin/bash
# Safe deployment script that handles Redis unavailability
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 "▶ 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

# Try to clear cache, but don't fail if Redis is unavailable
echo "  → Clearing application cache (may fail if Redis is down)..."
php artisan cache:clear || echo "  ⚠ Cache clear failed (Redis may be down), continuing..."

# Optimize application (skip cache optimize if Redis is unavailable)
echo "  → Optimizing config..."
php artisan config:cache

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

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

# Try to optimize cache, but don't fail if Redis is unavailable
echo "  → Optimizing application cache (may fail if Redis is down)..."
php artisan cache:optimize || echo "  ⚠ Cache optimize failed (Redis may be down), continuing..."

echo "✅ Deploy complete."