#!/usr/bin/bash

VER=$1

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

function install_ssa()
{
  PHP=$1
  if [ -e "$PHP" ]; then
    VERS=$("$PHP" --version | head -n1 | cut -d' ' -f2 | cut -c 1,3)
    if [[ ! "$VERS" =~ ^[0-9]{2}$ ]]; then
      return 1
    fi
    EXT_DIR=$("$PHP" -i | grep -e "^extension_dir" | cut -d"=" -f2 | tr ">" " " | sed 's/^ *//;s/ *$//')
    if [[ ! "$EXT_DIR" =~ ^/[a-zA-Z0-9/_.-]+$ ]] || [[ "$EXT_DIR" == *".."* ]]; then
      return 1
    fi
    ALT_SSA="/opt/alt/php$VERS/usr/lib$LIBS/php/modules/clos_ssa.so"
    CAGEFS_DIR="/usr/share/cagefs-skeleton$EXT_DIR"
    if [ -e "$ALT_SSA" -a -e "$EXT_DIR" -a -n "$EXT_DIR" ]; then
      rm -f "$EXT_DIR/clos_ssa.so"
      cp "$ALT_SSA" "$EXT_DIR"
      if [ -e "$CAGEFS_DIR" ]; then
        rm -f "$CAGEFS_DIR/clos_ssa.so"
        cp "$ALT_SSA" "$CAGEFS_DIR"
      fi
    fi
  fi
}

if [ -z "$VER" ]; then
  PHPS=$(ls /usr/local/php*/bin/php)
  for PHP in $PHPS
  do
    install_ssa "$PHP"
  done
else
  if [[ ! "$VER" =~ ^[0-9]+$ ]]; then
    echo "Error: invalid PHP version '$VER'" >&2
    exit 1
  fi
  PHP="/usr/local/php$VER/bin/php"
  install_ssa "$PHP"
fi
