#!/usr/bin/sh

# Synconix PECL wrapper:
# - per-slot pear.conf auto-create/repair
# - prevents PECL from editing php.ini (enables via php.d/*.ini)
# - auto-creates 50-<ext>.ini on install/upgrade; removes on uninstall

SELF="$(readlink -f "$0" 2>/dev/null || echo "$0")"
BIN_DIR="$(dirname "$SELF")"
SLOT="${BIN_DIR%/usr/bin}"
if [ ! -x "$SLOT/usr/bin/php" ]; then
  SLOT="$(cd "$BIN_DIR/../../.." 2>/dev/null && pwd)"
fi

export PATH="$SLOT/usr/bin:$PATH"
export PHPIZE="$SLOT/usr/bin/phpize"
export PHP_CONFIG="$SLOT/usr/bin/php-config"
export PHP_PEAR_PHP_BIN="${PHP_PEAR_PHP_BIN:-$SLOT/usr/bin/php}"

# Prefer existing pear.conf location if present (some builds use $SLOT/usr/etc, others $SLOT/etc)
if [ -z "${PEAR_SYSTEM_CONFIG:-}" ]; then
  if [ -f "$SLOT/usr/etc/pear.conf" ]; then
    export PEAR_SYSTEM_CONFIG="$SLOT/usr/etc/pear.conf"
    export PEAR_CONFIG_SYSCONFDIR="$SLOT/usr/etc"
  else
    export PEAR_SYSTEM_CONFIG="$SLOT/etc/pear.conf"
    export PEAR_CONFIG_SYSCONFDIR="$SLOT/etc"
  fi
fi

PHP_INI="$SLOT/etc/php.ini"
PHP_BIN="$SLOT/usr/bin/php"

# choose PHP binary (allow env override)
if [ -n "$PHP_PEAR_PHP_BIN" ]; then
  PHP="$PHP_PEAR_PHP_BIN"
else
  if [ "$PHP_BIN" = '@'php_bin'@' ]; then
    PHP=php
  else
    PHP="$PHP_BIN"
  fi
fi

# pick pear include path
if [ -n "${PHP_PEAR_INSTALL_DIR:-}" ]; then
  INCDIR="$PHP_PEAR_INSTALL_DIR"
  INCARG="-d include_path=$PHP_PEAR_INSTALL_DIR"
else
  if [ "$SLOT/usr/share/pear" = '@'php_dir'@' ]; then
    INCDIR="$(dirname "$0")"
    INCARG=""
  else
    INCDIR="$SLOT/usr/share/pear"
    INCARG="-d include_path=$SLOT/usr/share/pear"
  fi
fi

# ensure per-slot PEAR config points to THIS slot (avoid cross-slot bleed)
PEAR="$SLOT/usr/bin/pear"
CONF="$PEAR_SYSTEM_CONFIG"
PECL_DUMMY_INI="$SLOT/etc/pecl.ini"

[ -d "$(dirname "$CONF")" ] || mkdir -p "$(dirname "$CONF")" >/dev/null 2>&1 || :
[ -f "$PECL_DUMMY_INI" ] || : > "$PECL_DUMMY_INI" 2>/dev/null || :

# if existing config is broken, recreate it
if [ -s "$CONF" ]; then
  "$PEAR" -c "$CONF" -q config-show >/dev/null 2>&1 || rm -f "$CONF"
fi

[ -s "$CONF" ] || "$PEAR" -q config-create "$SLOT/usr/share/pear" "$CONF" >/dev/null 2>&1 || :
"$PEAR" -c "$CONF" -q config-set php_bin "$SLOT/usr/bin/php" system        >/dev/null 2>&1 || :
"$PEAR" -c "$CONF" -q config-set php_ini "$PECL_DUMMY_INI" system          >/dev/null 2>&1 || :
"$PEAR" -c "$CONF" -q config-set bin_dir "$SLOT/usr/bin" system            >/dev/null 2>&1 || :
"$PEAR" -c "$CONF" -q config-set php_dir "$SLOT/usr/share/pear" system     >/dev/null 2>&1 || :

# Run pecl (capture rc so we can post-process)
"$PHP" -C -q -c "$PHP_INI" $INCARG \
  -d date.timezone=UTC -d output_buffering=1 -d variables_order=EGPCS \
  -d safe_mode=0 -d register_argc_argv="On" \
  "$INCDIR/peclcmd.php" "$@"
rc=$?

cmd="${1:-}"

# Auto-enable installed extensions (INI drop-in only; never touch php.ini)
if [ $rc -eq 0 ]; then
  if [ "$cmd" = "install" ] || [ "$cmd" = "upgrade" ]; then

    # Resolve scan dir; only accept it if it is an existing directory.
    INI_SCAN_DIR="$("$PHP" -n -r 'echo (defined("PHP_CONFIG_FILE_SCAN_DIR") ? PHP_CONFIG_FILE_SCAN_DIR : "");' 2>/dev/null)"
    if [ -z "$INI_SCAN_DIR" ] || [ ! -d "$INI_SCAN_DIR" ]; then
      INI_SCAN_DIR="$SLOT/etc/php.d"
    fi
    [ -d "$INI_SCAN_DIR" ] || mkdir -p "$INI_SCAN_DIR" >/dev/null 2>&1 || :

    EXT_DIR="$("$PHP" -n -r 'echo ini_get("extension_dir");' 2>/dev/null)"

    for pkg in "$@"; do
      case "$pkg" in
        install|upgrade|--*|-*) continue ;;
        *)
          ext="${pkg##*/}"
          ext="${ext%-*}"

          case "$ext" in
            xdebug|pcov) loader="zend_extension"; value="$EXT_DIR/$ext.so" ;;
            *)           loader="extension";      value="$ext.so" ;;
          esac

          ini_file="$INI_SCAN_DIR/50-$ext.ini"
          if [ ! -f "$ini_file" ]; then
            printf "%s=%s\n" "$loader" "$value" > "$ini_file"
            echo ">>> Created $ini_file to enable $ext"
          fi

          # safety-net: if PECL wrote into php.ini, remove it (we manage via php.d)
          if [ -f "$PHP_INI" ]; then
            if [ "$loader" = "zend_extension" ]; then
              sed -i -E "/^[[:space:]]*zend_extension[[:space:]]*=[[:space:]]*\"?([^\";]*\/)?${ext}(\.so)?\"?[[:space:]]*(;.*)?$/Id" "$PHP_INI" 2>/dev/null || :
            else
              sed -i -E "/^[[:space:]]*extension[[:space:]]*=[[:space:]]*\"?([^\";]*\/)?${ext}(\.so)?\"?[[:space:]]*(;.*)?$/Id" "$PHP_INI" 2>/dev/null || :
            fi
          fi
        ;;
      esac
    done

  elif [ "$cmd" = "uninstall" ]; then

    INI_SCAN_DIR="$("$PHP" -n -r 'echo (defined("PHP_CONFIG_FILE_SCAN_DIR") ? PHP_CONFIG_FILE_SCAN_DIR : "");' 2>/dev/null)"
    if [ -z "$INI_SCAN_DIR" ] || [ ! -d "$INI_SCAN_DIR" ]; then
      INI_SCAN_DIR="$SLOT/etc/php.d"
    fi

    for pkg in "$@"; do
      case "$pkg" in
        uninstall|--*|-*) continue ;;
        *)
          ext="${pkg##*/}"
          ext="${ext%-*}"
          ini_file="$INI_SCAN_DIR/50-$ext.ini"
          [ -f "$ini_file" ] && rm -f "$ini_file" && echo ">>> Removed $ini_file"
        ;;
      esac
    done

  fi
fi

exit $rc
