#!/bin/bash
# ==============================================
# 🚀 Run Laravel Docker Stack with ACL fix
# ==============================================

current_user=$(whoami)
echo "Setting ACLs for user: $current_user"

# Ensure user exists
if ! id -u "$current_user" > /dev/null 2>&1; then
  echo "Error: user '$current_user' does not exist. Exiting."
  exit 1
fi

# Set ACL for ./app directory
sudo setfacl -R -m u:"$current_user":rwx ./app

# Build and start containers
docker compose up -d --build "$@"

# -------------------------------
# PSR-4 Autoloading via Composer
# -------------------------------
if docker compose ps -q php | grep -q .; then
    echo "Running Composer install as root inside PHP container..."
    docker compose exec -T --user 0 php bash -c "cd /var/www/app/workopia/ && composer install --no-dev --prefer-dist --ignore-platform-reqs"

    if [ $? -eq 0 ]; then
        echo "Composer installed successfully."
        echo "Fixing permissions for vendor and composer.lock..."
        sudo chown -R ${UID}:${GID} ./app/workopia/vendor
        sudo chown ${UID}:${GID} ./app/workopia/composer.lock
    else
        echo "⚠️ Composer install failed. Check PHP container logs."
    fi
else
    echo "⚠️ PHP container not running. Cannot run Composer install."
fi

# Optional: view container status
docker compose ps
sleep 7
docker compose ps
sleep 7
docker compose ps
