#!/bin/bash
set -e

APP_ENV="${ENV_APP_ENV:-local}"
APP_DEBUG=false

if [ "$APP_ENV" = 'local' ]; then
    APP_DEBUG=true
fi

create_env_file() {
    local target_file="$1"
    local environment="$2"
    local debug="$3"
    local app_key

    app_key="$(php -r 'echo bin2hex(random_bytes(16));')"

    sed -e "s/DB_HOST=localhost/DB_HOST=${ENV_DB_HOST:-localhost}/g" \
        -e "s/DB_PORT=3306/DB_PORT=${ENV_DB_PORT:-3306}/g" \
        -e "s/DB_DATABASE=homestead/DB_DATABASE=${ENV_DB_DATABASE:-homestead}/g" \
        -e "s/DB_USERNAME=homestead/DB_USERNAME=${ENV_DB_USER:-homestead}/g" \
        -e "s/DB_PASSWORD=secret/DB_PASSWORD=${ENV_DB_PASSWORD:-secret}/g" \
        -e "s/APP_ENV=local/APP_ENV=${environment}/g" \
        -e "s/APP_DEBUG=true/APP_DEBUG=${debug}/g" \
        -e "s/APP_KEY=SomeRandomKey!!!/APP_KEY=${app_key}/g" \
        < .env.example \
        > "$target_file"
}

case "${1:-}" in
    lint)
        exec /app/vendor/bin/phpcs --standard=PSR2 app/
        ;;
    test)
        if [ ! -f .env.testing ]; then
            create_env_file .env.testing testing false
        fi
        shift
        exec /app/vendor/bin/phpunit "$@"
        ;;
    artisan)
        shift
        exec php artisan "$@"
        ;;
esac

if [ ! -f .env ]; then
    create_env_file .env "$APP_ENV" "$APP_DEBUG"
fi

if [ -n "${ENV_DB_HOST:-}" ] && [ "${SKIP_MIGRATIONS:-false}" != 'true' ]; then
    php artisan migrate --force
fi

exec "$@"
