#!/usr/bin/bash

VER=$1

LIBS=""
MACHINE_TYPE=`uname -m`
if [ ${MACHINE_TYPE} == 'x86_64' ]; then
   LIBS="64"
else
   LIBS=""
fi

function install_xray()
{
  PHP=$1
  if [ -e "$PHP" ]; then
    VERS=$($PHP --version | head -n1 | cut -d' ' -f2 | cut -c 1,3)
    EXT_DIR=$($PHP -i | grep -e "^extension_dir" | cut -d"=" -f2 | tr ">" " " | sed 's/^ *//;s/ *$//')
    ALT_XRAY="/opt/alt/php$VERS/usr/lib$LIBS/php/modules/xray.so"
    CAGEFS_DIR="/usr/share/cagefs-skeleton$EXT_DIR"
    if [ -e $ALT_XRAY -a -e $EXT_DIR -a -n "$EXT_DIR" ]; then
      # `install -m 0755` rather than `cp`: cp derives the mode of a freshly
      # created destination from the source mode masked by the CALLER's umask,
      # so any invoker running under a restrictive umask silently produced a
      # 0700 xray.so that PHP could no longer dlopen (ZD 290458). The mode of a
      # module every PHP process has to load must not depend on ambient state.
      # rm -f before install is deliberate and kept: it unlinks the old inode so
      # already-running PHP processes keep their existing mapping instead of
      # having a mapped .so truncated underneath them.
      rm -f "$EXT_DIR/xray.so"
      install -m 0755 $ALT_XRAY $EXT_DIR
      if [ -e $CAGEFS_DIR ]; then
        rm -f "$CAGEFS_DIR/xray.so"
        install -m 0755 $ALT_XRAY $CAGEFS_DIR
      fi
    fi
  fi
}

if [ -z "$VER" ]; then
  PHPS=$(ls /usr/local/php*/bin/php)
  for PHP in $PHPS
  do
    install_xray $PHP
  done
else
  # VER is interpolated into an executable path; restrict to a phpNN version
  # directory name (exactly two digits) to prevent path traversal.
  if [[ ! "$VER" =~ ^[0-9]{2}$ ]]; then
    echo "da_cp_xray: invalid PHP version '$VER' (expected two digits)" >&2
    exit 1
  fi
  PHP="/usr/local/php$VER/bin/php"
  install_xray "$PHP"
fi
