#!/usr/bin/env bash

# Check running directory...
if [ "$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )" != "$(pwd)" ]; then
    echo "Script should be run from php-demandware-xml folder" >&2
    exit 1;
fi

# Ensure that Docker is running...
if ! docker info > /dev/null 2>&1; then
    echo "Docker is not running." >&2
    exit 1
fi

# Function to run a command on Docker instance...
function docker-php() {
    docker run -it --rm --name php-demandware-xml -v "$PWD":/app -w /app "ghcr.io/fusionspim/php-demandware-xml/php-cli:latest" "$@"
}

# Handle commands...
if [ $# -gt 0 ]; then
    # Initiate a Bash shell...
    if [ "$1" == "shell" ]; then
        docker-php sh

    # Proxy PHP commands...
    elif [ "$1" == "php" ]; then
        shift 1
        docker-php php "$@"

    # Proxy PHPUnit commands...
    elif [ "$1" == "phpunit" ]; then
        shift 1
        docker-php php vendor/bin/phpunit "$@"

    # Proxy Composer commands...
    elif [ "$1" == "composer" ]; then
        shift 1
        docker-php composer "$@"

    fi
else
    # Show command usage instructions...
    echo "Usage: ./php-demandware-xml shell"
    echo "       ./php-demandware-xml php <command>"
    echo "       ./php-demandware-xml phpunit <command>"
    echo "       ./php-demandware-xml composer <command>"
fi
