#!/bin/bash
# Not working on windows symlinks
DIR="$(realpath $(dirname "$(readlink -f "$0")")/..)"

PHP_VERSION=$1 # Without dot
WITH_PROFILER=$2

if [[ -z "${PHP_VERSION}" ]]; then PHP_VERSION=81; fi

PHP_FPM_CONTAINER=$(docker ps | grep "php${PHP_VERSION}" | awk '{print $1}')
WORKSPACE_CONTAINER=$(docker ps | grep "workspace${PHP_VERSION}" | awk '{print $1}')

PHP_FPM_XDEBUG_EXT_PATH=/usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
WORKSPACE_XDEBUG_EXT_PATH=/etc/php/${PHP_VERSION}/cli/conf.d/20-xdebug.ini

SED_XDEBUG_ON="sed -i 's/^;zend_extension=/zend_extension=/g'"

docker exec -it "${PHP_FPM_CONTAINER}" bash -c "${SED_XDEBUG_ON} ${PHP_FPM_XDEBUG_EXT_PATH}"
docker exec -it "${WORKSPACE_CONTAINER}" bash -c "${SED_XDEBUG_ON} ${WORKSPACE_XDEBUG_EXT_PATH}"

echo "Choice PHP_VERSION: $PHP_VERSION"

if [ "${PHP_VERSION}" -ne 74 ]; then
  if [ -n "${WITH_PROFILER}" ]; then
    SED_DEBUG_OR_PROFILER_MODE_ON="sed -i 's/^xdebug.profiler_enable=.*/xdebug.profiler_enable=1/g'"
  fi
else
  if [ -n "${WITH_PROFILER}" ]; then
    SED_DEBUG_OR_PROFILER_MODE_ON="sed -i 's/^xdebug.mode=.*/xdebug.mode=profile/g'"
  else
    SED_DEBUG_OR_PROFILER_MODE_ON="sed -i 's/^xdebug.mode=.*/xdebug.mode=debug/g'"
  fi
fi

docker exec -it "${PHP_FPM_CONTAINER}" bash -c "${SED_DEBUG_OR_PROFILER_MODE_ON} ${PHP_FPM_XDEBUG_EXT_PATH}"
docker exec -it "${WORKSPACE_CONTAINER}" bash -c "${SED_DEBUG_OR_PROFILER_MODE_ON} ${WORKSPACE_XDEBUG_EXT_PATH}"
