#!/bin/bash

# Get the current directory of the script
PROJECT_PATH=$(dirname $(realpath $0))

# Web server user (update if different)
WEB_USER="www-data"

# Change to project directory
cd $PROJECT_PATH || exit

# Pull latest code from repository
git pull origin main

# Install/update Composer dependencies
composer install --no-interaction --prefer-dist --optimize-autoloader

# Install Laravel UI package and generate auth scaffolding
composer require laravel/ui
php artisan ui bootstrap --auth # Change to vue or react if needed

# Install npm dependencies and compile assets
npm install
npm run dev

# Run database migrations
php artisan migrate --force

# Set permissions and ownership
sudo chmod -R 775 storage
sudo chmod -R 775 bootstrap/cache
sudo chown -R $WEB_USER:$WEB_USER storage
sudo chown -R $WEB_USER:$WEB_USER bootstrap/cache

# Check SELinux and set context if applicable
if command -v chcon &> /dev/null; then
    sudo chcon -R -t httpd_sys_rw_content_t storage
    sudo chcon -R -t httpd_sys_rw_content_t bootstrap/cache
fi

# Clear and cache configurations, routes, and views
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "Deployment complete."
