#!/bin/bash
echo "Running deployment script..."

set -e  # Exit immediately if a command exits with a non-zero status.
set -x  # Print commands and their arguments as they are executed.

# Check if SERVICE_API_FOLDER variable is set
if [ -z "$SERVICE_API_FOLDER" ]; then
  echo "SERVICE_API_FOLDER variable is not set!"
  exit 1
fi

# Detect PHP version
if command -v php8.3 &> /dev/null; then
  PHP_CMD="php8.3"
else
  PHP_CMD="php"  # Fallback to default PHP
fi

echo "Using PHP version: $($PHP_CMD -v | head -n 1)"

# Define the directory and path using the SERVICE_API_FOLDER variable
DIRECTORY="/var/www/html/$SERVICE_API_FOLDER"
HTACCESS_PATH="$DIRECTORY/public/.htaccess"
REWRITE_BASE="/$SERVICE_API_FOLDER"

# Navigate to the application directory
cd "$DIRECTORY"

# Put the application in maintenance mode
$PHP_CMD artisan down

# Install or update dependencies
$PHP_CMD /usr/local/bin/composer install --no-interaction --no-dev --prefer-dist

# Run database migrations
$PHP_CMD artisan migrate --no-interaction --force

# Cache the configuration
$PHP_CMD artisan config:cache

# Navigate to the public directory
cd public

# Check if .htaccess exists
if [ ! -f .htaccess ]; then
  echo ".htaccess file not found!"
  exit 1
fi

# Check for and update .htaccess file
grep -q "^[[:space:]]*RewriteBase $REWRITE_BASE/" .htaccess || \
  sed -i "/RewriteEngine On/a RewriteBase $REWRITE_BASE/" .htaccess

# Return to the root directory
cd ..

# Bring the application out of maintenance mode
$PHP_CMD artisan up

echo "Deployment completed successfully."
