#!/bin/bash

# Startup script for the inventory management container

echo "Starting Inventory Management System..."

# Check if database is available
echo "Waiting for database connection..."
while ! mysqladmin ping -h"$DB_HOST" -u"$DB_USER" -p"$DB_PASS" --silent; do
    echo "Database not ready, waiting..."
    sleep 2
done

echo "Database is ready!"

# Create uploads directory if it doesn't exist
mkdir -p /var/www/html/uploads

# Set proper permissions for uploads directory
chown -R www-data:www-data /var/www/html/uploads
chmod -R 755 /var/www/html/uploads

# Create necessary directories for file uploads
mkdir -p /var/www/html/uploads/documents
mkdir -p /var/www/html/uploads/images
mkdir -p /var/www/html/uploads/temp

# Set permissions for subdirectories
chown -R www-data:www-data /var/www/html/uploads/*
chmod -R 755 /var/www/html/uploads/*

# Check if .htaccess exists, create if not
if [ ! -f /var/www/html/.htaccess ]; then
    echo "Creating .htaccess file..."
    cat > /var/www/html/.htaccess << EOF
# Enable URL rewriting
RewriteEngine On

# API endpoints
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^api/(.*)$ api/$1.php [L]

# Frontend routes (for SPA)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.html [L]

# Security headers
<IfModule mod_headers.c>
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# PHP settings
php_value upload_max_fileSize ${UPLOAD_MAX_SIZE:-10M}
php_value post_max_size ${UPLOAD_MAX_SIZE:-10M}
php_value max_execution_time 300
EOF

    chown www-data:www-data /var/www/html/.htaccess
fi

# Display company information
echo "==============================================="
echo "Company: $(getenv 'COMPANY_NAME' 'Inventory Management')"
echo "Email: $(getenv 'COMPANY_EMAIL' 'info@company.com')"
echo "Phone: $(getenv 'COMPANY_PHONE' '+358 123 456 789')"
echo "==============================================="

echo "Starting Apache..."
exec apache2-foreground
