#!/bin/bash

main() {
    if [ "$IS_API_WORKER" = "true" ]; then
        # This is the API worker, skip setup and just run the command
        exec "$@"
    else
        # This is the API service, run full setup
        prep_file_permissions
        prep_storage
        wait_for_db
        apply_db_migrations
        run_init_project
        run_server "$@"
    fi
}

prep_file_permissions() {
    chmod a+x ./artisan
}

prep_storage() {
    # Create Laravel-specific directories
    mkdir -p /persist/storage/framework/cache/data
    mkdir -p /persist/storage/framework/sessions
    mkdir -p /persist/storage/framework/views

    # Set permissions for the entire storage directory
    chown -R www-data:www-data /persist/storage
    chmod -R 775 /persist/storage

    # Create symlink to the correct storage location
    ln -sf /persist/storage /usr/share/nginx/html/storage

    touch /var/log/opnform.log
    chown www-data /var/log/opnform.log

    # Ensure proper permissions for the storage directory
    chown -R www-data:www-data /usr/share/nginx/html/storage
    chmod -R 775 /usr/share/nginx/html/storage
}

wait_for_db() {
    echo "Waiting for DB to be ready"
    until ./artisan migrate:status 2>&1 | grep -q -E "(Migration table not found|Migration name)"; do
        sleep 1
    done
}

apply_db_migrations() {
    echo "Running DB Migrations"
    ./artisan migrate
}

run_init_project() {
    echo "Running app:init-project command"
    ./artisan app:init-project
}

run_server() {
    echo "Starting server $@"
    exec /usr/local/bin/docker-php-entrypoint "$@"
}

main "$@"