#!/bin/bash
# cPanel Post-Deployment Setup Script
# Run this AFTER uploading to cPanel

echo "=== Laravel cPanel Setup ==="

# Set correct permissions
echo "Setting permissions..."
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod -R 775 storage bootstrap/cache
chmod 644 .env

# CRITICAL: Remove any symlinks first (prevents "File exists" error)
echo "Checking for symlinks..."
if [ -L "public/storage" ]; then
    echo "Removing existing symlink..."
    rm -f public/storage
    echo "✓ Symlink removed"
fi

# Ensure public/storage is a REAL directory
if [ ! -d "public/storage" ]; then
    mkdir -p public/storage
    echo "✓ Created public/storage directory"
else
    echo "✓ public/storage exists"
fi

# Ensure storage/app/public exists
if [ ! -d "storage/app/public" ]; then
    mkdir -p storage/app/public
    echo "✓ Created storage/app/public directory"
fi

# Copy storage files to public/storage (instead of symlink)
echo "Syncing storage files..."
if [ -d "storage/app/public" ] && [ "$(ls -A storage/app/public 2>/dev/null)" ]; then
    rsync -av --ignore-existing storage/app/public/ public/storage/ 2>/dev/null || cp -rn storage/app/public/* public/storage/ 2>/dev/null || true
    echo "✓ Storage files synced"
else
    echo "✓ No files to sync yet"
fi

# Clear and cache config
echo "Optimizing Laravel..."
php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear

php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "=== Setup Complete ==="
echo "Remember to update .env with production database credentials!"
