#!/bin/bash

# Fix Storage Symlink and Permissions for Laravel on Hostinger/CyberPanel
# Run this script on your production server via SSH

# Navigate to your Laravel project directory
# Replace 'bondacare.online' with your actual domain
cd /home/bondacare.online/public_html

# 1. Ensure storage directories exist
echo "Creating storage directories..."
mkdir -p storage/framework/cache/data
mkdir -p storage/framework/sessions
mkdir -p storage/framework/views
mkdir -p storage/framework/testing
mkdir -p storage/logs
mkdir -p storage/app/public
mkdir -p storage/app/templates
mkdir -p storage/app/private
mkdir -p storage/app/temp

# 2. Remove existing symlink if it exists (broken or incorrect)
echo "Removing existing storage symlink if present..."
rm -f public/storage

# 3. Create the storage symlink using Laravel artisan
echo "Creating storage symlink..."
php artisan storage:link

# If artisan command fails, create symlink manually:
# ln -s ../storage/app/public public/storage

# 4. Set proper permissions
echo "Setting permissions..."
chmod -R 775 storage
chmod -R 775 bootstrap/cache

# 5. Set ownership (replace 'cyberpanel' with your web server user if different)
echo "Setting ownership..."
chown -R cyberpanel:cyberpanel storage
chown -R cyberpanel:cyberpanel bootstrap/cache
chown -R cyberpanel:cyberpanel public/storage

# 6. Verify the symlink was created correctly
echo "Verifying symlink..."
ls -la public/storage

# 7. Clear Laravel caches
echo "Clearing Laravel caches..."
php artisan cache:clear
php artisan config:clear
php artisan view:clear
php artisan route:clear

# 8. Rebuild caches
echo "Rebuilding caches..."
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "Storage setup complete!"
echo "Test by visiting: https://yourdomain.com/storage (should show directory listing or 403)"
