#!/bin/bash
set -e
echo "Welcome to SendPortal Entrypoint Script!"

# Configure secret paths with defaults. 
# Docker Comose uses /run/secrets 
# K8s will likely use /etc/secrets or custom podspec path. 
SECRETS_PATH=${SECRETS_PATH:-/run/secrets}
ENV_SECRET_PATH="${SECRETS_PATH}/sendportal_env"
DB_SECRET_PATH="${SECRETS_PATH}/db_password"

# Set database host with default
if [ -z "$DB_HOST" ]; then
    echo "DB_HOST not set, defaulting to 'db'"
    DB_HOST="db"
fi


# check if database is ready
wait_for_db() {
    echo "Waiting for database to be ready..."
    while ! mysqladmin ping -h"$DB_HOST" -u"$DB_USERNAME" -p"$DB_PASSWORD" --silent; do
        sleep 1
    done
}

validate_app_key() {
    local env_file=$1
    if ! grep -q "^APP_KEY=" "$env_file"; then
        echo "APP_KEY not found in .env file"
        return 1
    fi
    
    local app_key=$(grep "^APP_KEY=" "$env_file" | cut -d '=' -f2)
    if [ -z "$app_key" ]; then
        echo "APP_KEY is empty"
        return 1
    fi
    
    return 0
}


# Set database password from secret
DB_PASSWORD=$(cat $DB_SECRET_PATH)

# Validate required environment variables
for var in  DB_USERNAME DB_PASSWORD; do
    if [ -z "${!var}" ]; then
        echo "Error: $var environment variable is not set"
        exit 1
    fi
done

# Check if .env file exists in secrets. If not, prep for web wizard.
if [ -f "$ENV_SECRET_PATH" ]; then
    echo ".env file found in secrets. Copying to application directory."
    cp /run/secrets/sendportal_env /var/www/html/.env
    
else
    # Assume we will install using the wizard via web browser.
    echo "No .env file found in secrets. Setting up for wizard installation..."
    echo "APP_KEY=" > /var/www/html/.env
    echo "To Complete Setup go to $APP_URL/setup"
fi

wait_for_db
if ! validate_app_key "/var/www/html/.env"; then
    echo "Generating new APP_KEY..."
    php artisan key:generate
fi

echo "Running artisan vendor:publish..." 
php artisan vendor:publish --all --force

echo "Running migrations..."
php artisan migrate --force

echo "Running migrations for sql based job queues..."
# php artisan queue:table  # Create the jobs table
# php artisan migrate --force

echo "Fixing log permissions..."
touch /var/www/html/storage/logs/laravel.log
chown -R www-data:www-data /var/www/html/storage/logs

echo "Starting Apache for SendPortal..."
# Start Apache in foreground
exec apache2-foreground