#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

# Configuration
WEB_USER="jamie"
WEB_GROUP="www-data"

echo "🚀 Starting Laravel/Statamic project setup..."

# 1. Pre-flight Permissions
echo "🔓 Unlocking storage and cache for installation scripts..."
# Granting ownership back to jamie so composer can write to existing cache files
sudo chown -R $WEB_USER:$WEB_GROUP storage bootstrap/cache || true
sudo chmod -R ug+rwx storage bootstrap/cache || true

# 2. Git Configuration
echo "⚙️ Configuring Git..."
git config receive.denyCurrentBranch updateInstead

# 3. Dependency Installation
echo "📦 Installing PHP dependencies..."
composer install --no-interaction --prefer-dist --optimize-autoloader

echo "📦 Installing Node dependencies..."
npm install

# 4. Environment File Check
if [ ! -f .env ]; then
    if [ -f .env.example ]; then
        echo "📄 .env file not found. Copying .env.example to .env..."
        cp .env.example .env
    else
        echo "⚠️ No .env or .env.example found. Skipping environment setup."
    fi
fi

# 5. Laravel Commands
echo "🔑 Generating application key..."
php artisan key:generate

echo "🔗 Creating storage symlink..."
php artisan storage:link || true 

# 6. Final Ubuntu/Laravel Permissions
echo "🔒 Securing final permissions for $WEB_USER:$WEB_GROUP..."

# Set explicit owner and group for the entire project (including new vendor/node_modules)
sudo chown -R $WEB_USER:$WEB_GROUP .

# Set standard permissions safely, EXCLUDING node_modules and vendor 
# to protect Vite, PHPUnit, and other package executables
sudo find . -type d -not -path "*/node_modules*" -not -path "*/vendor*" -exec chmod 755 {} \;
sudo find . -type f -not -path "*/node_modules*" -not -path "*/vendor*" -exec chmod 644 {} \;

# Ensure artisan and this setup script remain executable
sudo chmod +x artisan setup.sh || true

# Grant the web server group (and user) full read/write/execute on storage and cache again
sudo chmod -R ug+rwx storage bootstrap/cache

echo "✅ Setup complete! Your project is ready."