#!/usr/bin/env bash
# Fix file/folder permissions after cPanel ZIP extract (vendor 500 errors, storage write fails)
# Usage: bash fix-cpanel-permissions.sh
#        bash fix-cpanel-permissions.sh /home/user/ecommerce

set -e

ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}"
if [ -f "$ROOT/artisan" ]; then
    :
elif [ -f "$(dirname "$0")/artisan" ]; then
    ROOT="$(cd "$(dirname "$0")" && pwd)"
else
    ROOT="$(pwd)"
fi

cd "$ROOT"

echo "==> Fixing cPanel permissions in: $ROOT"

fix_tree() {
    local dir="$1"
    local dmode="$2"
    local fmode="$3"
    [ -d "$dir" ] || return 0
    find "$dir" -type d -exec chmod "$dmode" {} \; 2>/dev/null || true
    find "$dir" -type f -exec chmod "$fmode" {} \; 2>/dev/null || true
}

# --- vendor (ZIP extract-এ সবচেয়ে বেশি problem) ---
if [ -d vendor ]; then
    echo "    vendor/ ..."
    fix_tree vendor 755 644
    if [ -d vendor/bin ]; then
        find vendor/bin -type f -exec chmod 755 {} \; 2>/dev/null || true
    fi
    if [ -d vendor/itsquare/sms-gateway ]; then
        fix_tree vendor/itsquare/sms-gateway 755 644
    fi
else
    echo "    WARNING: vendor/ missing — upload incomplete?"
fi

# --- packages (local SMS gateway path) ---
if [ -d packages ]; then
    echo "    packages/ ..."
    fix_tree packages 755 644
fi

# --- Laravel writable dirs ---
echo "    storage/ + bootstrap/cache/ ..."
mkdir -p \
    storage/app/public \
    storage/framework/cache/data \
    storage/framework/sessions \
    storage/framework/views \
    storage/logs \
    bootstrap/cache

touch storage/logs/laravel.log 2>/dev/null || true
chmod -R 775 storage bootstrap/cache 2>/dev/null || true
find storage bootstrap/cache -type f -exec chmod 664 {} \; 2>/dev/null || true

# --- read-only code (safe defaults after extract) ---
for dir in app config database routes resources bootstrap; do
    if [ -d "$dir" ]; then
        echo "    $dir/ ..."
        fix_tree "$dir" 755 644
    fi
done

# bootstrap/cache must stay writable after fix_tree
chmod -R 775 bootstrap/cache 2>/dev/null || true

# --- public assets ---
if [ -d public ]; then
    echo "    public/ ..."
    fix_tree public 755 644
fi

# --- core files ---
[ -f artisan ] && chmod 755 artisan
[ -f composer.json ] && chmod 644 composer.json
[ -f composer.lock ] && chmod 644 composer.lock
[ -f .htaccess ] && chmod 644 .htaccess
[ -f public/.htaccess ] && chmod 644 public/.htaccess

# .env — not world-readable
if [ -f .env ]; then
    chmod 640 .env 2>/dev/null || chmod 600 .env 2>/dev/null || true
fi

echo "==> Permissions fixed (vendor 755/644, storage 775, bootstrap/cache 775)"
