#!/bin/sh
set -e

# Load environment variables from .env file if present
if [ "$ENV" = "local" ]; then
    if [ -f .env ]; then
        export $(grep -v '^#' .env | xargs)
    fi
fi
echo "Starting setup script..."

# Copy configuration files
echo "Copying necessary files..."
sudo cp /var/www/composer.json /var/www/html
sudo cp /var/www/composer.lock /var/www/html

# Provision Magento Marketplace auth from a runtime secret (kept out of the image).
# With the compose `.:/var/www/html` bind mount the host auth.json is already at the
# target AND is the same file as the secret, so skip the self-copy in that case.
AUTH_SECRET="${AUTH_JSON_FILE:-/run/secrets/magento_auth}"
AUTH_DEST=/var/www/html/auth.json
if [ -f "$AUTH_SECRET" ]; then
    if [ "$AUTH_SECRET" -ef "$AUTH_DEST" ]; then
        echo "auth.json already in place (same file as secret); skipping copy"
    else
        sudo cp "$AUTH_SECRET" "$AUTH_DEST"
    fi
    sudo chown www-data:www-data "$AUTH_DEST" 2>/dev/null || true
    sudo chmod 600 "$AUTH_DEST"
else
    echo "ERROR: Magento auth.json secret not found at $AUTH_SECRET" >&2
    echo "Provide it via the 'magento_auth' Docker secret (compose: secrets.magento_auth.file=./auth.json) or set AUTH_JSON_FILE." >&2
    exit 1
fi

if [ "$ENV" = "local" ]; then
  if [ ! -d /var/www/html/app/code ]; then
      echo "Syncing app/code directory..."
      sudo rsync -av --delete /var/www/app/code /var/www/html/app/
  fi
  if [ ! -d /var/www/html/app/design ] && [ -d /var/www/app/design ] && [ "$(ls -A /var/www/app/design)" ]; then
      echo "Syncing app/design directory..."
      sudo rsync -av --delete /var/www/app/design /var/www/html/app/
  fi
  if [ ! -d /var/www/html/node ]; then
      echo "Syncing node directory..."
      sudo rsync -av --delete --exclude 'credentials.txt' --exclude 'node_modules/' /var/www/node /var/www/html/
  fi
else
  sudo rsync -av --delete --exclude 'credentials.txt' --exclude 'node_modules/' /var/www/node /var/www/html/
  sudo rsync -av --delete /var/www/python /var/www/html/
  sudo rsync -av --delete /var/www/app/code /var/www/html/app/
  if [ -d /var/www/app/design ] && [ "$(ls -A /var/www/app/design)" ]; then
      echo "Syncing app/design directory..."
      sudo rsync -av --delete /var/www/app/design /var/www/html/app/
  else
      echo "app/design not present, skipping."
  fi
fi
# Set ownership and permissions
echo "Setting ownership and permissions..."
if [ "$ENV" = "local" ]; then
    sudo chown -R www-data:www-data /var/www/html/
  sudo chmod -R 777 /var/www/html/
fi
# Install Composer dependencies
echo "Installing Composer packages..."
composer install --ignore-platform-reqs

# Install required PHP packages — only on fresh setup (before env.php exists)
if [ ! -f app/etc/env.php ]; then
    REQUIRED_PACKAGES="mpdf/mpdf:^8.2 spipu/html2pdf:^5.2 clegginabox/pdf-merger:dev-master google/apiclient:^2.0 stripe/stripe-payments:^4.0 tecnickcom/tcpdf:6.5.0 rhysnhall/etsy-php-sdk:^0.4.0 google/auth:^1.28 google/photos-library:^1.7 laminas/laminas-stdlib"
    for PACKAGE_VERSION in $REQUIRED_PACKAGES; do
        PACKAGE=$(echo "$PACKAGE_VERSION" | cut -d: -f1)
        if echo "$PACKAGE_VERSION" | grep -q ':'; then
            VERSION=$(echo "$PACKAGE_VERSION" | cut -d: -f2-)
        else
            VERSION=""
        fi
        echo "Checking package $PACKAGE..."
        if ! composer show | grep -q "^$PACKAGE"; then
            if [ -n "$VERSION" ]; then
                echo "Installing $PACKAGE:$VERSION..."
                composer require "$PACKAGE:$VERSION" --ignore-platform-reqs
            else
                echo "Installing $PACKAGE (no version specified)..."
                composer require "$PACKAGE" --ignore-platform-reqs
            fi
        else
            echo "$PACKAGE is already installed."
        fi
    done
fi

# Check if Magento is installed
if [ ! -f app/etc/env.php ]; then
    echo "Installing Magento..."
    php bin/magento setup:install \
        --base-url="$MAGENTO_HOST" \
        --db-host="$DB_HOST" \
        --db-name="$DB_NAME" \
        --db-user="$DB_USER" \
        --db-password="$DB_PASSWORD" \
        --backend-frontname="$MAGENTO_ADMIN_FRONTNAME" \
        --admin-firstname="$MAGENTO_ADMIN_FIRST_NAME" \
        --admin-lastname="$MAGENTO_ADMIN_LAST_NAME" \
        --admin-email="$MAGENTO_ADMIN_EMAIL" \
        --admin-user="$MAGENTO_ADMIN_USER" \
        --admin-password="$MAGENTO_ADMIN_PASSWORD" \
        --language="$MAGENTO_LOCALE" \
        --currency="$MAGENTO_CURRENCY" \
        --timezone="$MAGENTO_TIMEZONE" \
        --opensearch-host="$ES_HOST" \
        --opensearch-port="$ES_PORT" \
        --use-rewrites=1 \
        --search-engine="$ES_ENGINE" \
        --cleanup-database

    echo "Disabling unnecessary features..."
    php bin/magento config:set dev/static/sign 0
    if [ "$ENV" = "local" ]; then
        php bin/magento module:disable Magento_TwoFactorAuth Magento_AdminAdobeImsTwoFactorAuth
    fi
else
    echo "Magento is already installed."
fi

# Apply patches
echo "Applying patches..."
# pub/ patch overrides are optional and not present in every checkout; copy only if provided.
if [ -d /var/www/patches/pub ] && [ -n "$(ls -A /var/www/patches/pub 2>/dev/null)" ]; then
    sudo cp -r /var/www/patches/pub/* /var/www/html/pub/
fi
sudo cp /var/www/patches/index.php /var/www/html/pub/index.php
# Solve admin side loader issue
sudo mkdir -p /var/www/html/lib/web/mage/requirejs/
sudo cp /var/www/patches/mixins.js /var/www/html/lib/web/mage/requirejs/mixins.js
# Integration patches add qeueue entry for "catalog,search" product for sync
# Apply custom patch only once per container SessionReaper vulnerability (CVE-2025-54236)
CUSTOM_PATCH_FILE="/var/www/patches/VULN-32437_2.4.X.patch"
PATCH_MARKER="/var/www/html/var/.custom_patch_applied"

if [ -f "$CUSTOM_PATCH_FILE" ]; then
    if [ ! -f "$PATCH_MARKER" ]; then
        echo "Applying custom patch from $CUSTOM_PATCH_FILE"
        if (cd /var/www/html && sudo patch -p1 --forward --reject-file=/dev/null < "$CUSTOM_PATCH_FILE"); then
            echo "Custom patch applied successfully."
        else
            echo "Custom patch already included in this Magento version, skipping."
        fi
        sudo touch "$PATCH_MARKER"
    else
        echo "Custom patch already applied, skipping."
    fi
else
    echo "Custom patch file not found at $CUSTOM_PATCH_FILE, skipping."
fi

# Clear caches
echo "Clearing Magento caches..."
rm -rf generated/* pub/static/* var/view_preprocessed/* var/cache/* var/page_cache/*
# Set ownership and permissions only on the directories we cleared
echo "Setting ownership and permissions..."
for dir in generated pub/static var/view_preprocessed var/cache var/page_cache; do
    if [ -d "$dir" ]; then
        sudo chown -R www-data:www-data "$dir"
        sudo chmod -R 775 "$dir"
    fi
done
# Enable/Disable modules
echo "Managing modules..."

# Magento setup tasks
echo "Running Magento setup tasks..."
php bin/magento setup:upgrade --safe-mode=1 --data-restore=1
if [ "$ENV" = "local" ]; then
    php bin/magento deploy:mode:set developer
    php bin/magento setup:di:compile
    php -d memory_limit=-1 bin/magento setup:static-content:deploy -f
else
  php bin/magento deploy:mode:set production --skip-compilation
  php bin/magento setup:di:compile
  php -d memory_limit=-1 bin/magento setup:static-content:deploy -f
fi
if [ -d /var/www/html/pub/media/customer_address ]; then
  echo "Setting permissions for customer_address directory..."
  sudo chmod -R 000 /var/www/html/pub/media/customer_address
  sudo chmod -R 000 /var/www/html/pub/media/custom_options
fi

# Install PX Data (First time only)
# php bin/magento brushyourideas:install
# php bin/magento brushyourideas:sampledata --action=live


# Install Headless Sample Data (First time only)
#php bin/magento headless:sampledata

# Install Terser dependencies for minification
# if [ ! -d node_modules ]; then
#     echo "Installing Terser dependencies..."
#     npm install --production
# fi

# echo "Minifying JavaScript..."
# npm run minify

php bin/magento cache:clean
php bin/magento cache:flush

# Precompress static assets so nginx can serve .br/.gz directly updated for gzip and brotli compression
# Commented as of now as we have applied brotli compression in the nginx configuration with cloudflare
# compress_static_assets() {
#   echo "Precompressing static assets (gzip + brotli)..."
#   cd /var/www/html || return
#   # Find compressible files >256 bytes in pub/
#   find pub/ -type f \( -name '*.js' -o -name '*.css' -o -name '*.html' -o -name '*.json' -o -name '*.svg' -o -name '*.xml' \) -size +256c -print0 |
#     xargs -0 -n1 -P4 sh -c '
#       for f; do
#         # Skip if not a full path or invalid
#         [ -f "$f" ] || { echo "Skipping non-file: $f"; continue; }
#         rm -f "${f}.gz" "${f}.br"
#         gzip -9 -c "$f" > "${f}.gz" || { echo "Gzip failed for $f"; continue; }
#         if command -v brotli >/dev/null 2>&1; then
#           brotli -q 4 --best -f -o "${f}.br" "$f" || echo "Brotli failed for $f"
#         fi
#         echo "Compressed: $f"
#       done
#     ' sh
#   echo "Precompression done."
# }
# compress_static_assets


# Restart RabbitMQ consumers
php bin/magento queue:consumers:restart

sudo rm -rf /var/www/html/node/node_modules
# Check and install Node.js dependencies
if [ ! -d /var/www/html/node/node_modules ]; then
    echo "Installing Node.js dependencies..."
    cd /var/www/html/node
    sudo rm -rf /var/www/html/node/node_modules/ /var/www/html/node/package-lock.json
    sudo npm install
fi
# Build node for outputs
echo "Building node packages..."
cd /var/www/html/node
# Rebuild native canvas binding against container libraries.
# This prevents startup crashes when host-built node_modules are bind-mounted.
echo "Rebuilding canvas native module..."
if ! sudo /usr/local/bin/npm rebuild canvas; then
    echo "Warning: canvas rebuild failed; gangsheet/output generation may fail."
fi
sudo /usr/local/bin/npm run build

# Configure PHP-FPM
echo "Configuring PHP-FPM..."
sudo sed -i -e 's/^pm\.max_children =.*/pm.max_children = 61/' \
    -e 's/^pm\.start_servers =.*/pm.start_servers = 15/' \
    -e 's/^pm\.min_spare_servers =.*/pm.min_spare_servers = 15/' \
    -e 's/^pm\.max_spare_servers =.*/pm.max_spare_servers = 45/' \
    /usr/local/etc/php-fpm.d/www.conf

# Start services
echo "Starting services..."
sudo service nginx start
sudo service cron start
sudo service postfix start
# Start supervisord
exec supervisord -c /etc/supervisor/supervisord.conf
