
#!/bin/bash
# autofix-cwp-php.sh
# Description: A script to fix PHP compilation issues and ld/ldconfig problems on CentOS 8 / AlmaLinux 8 with CWP.
# Compatible with: CentOS Web Panel, AlmaLinux 8, CentOS 8
# Author: Ali Musa Axadle Server Manager


echo "=== CentOS Web Panel PHP Auto-Fix Script ==="
echo "Updating system and installing development tools..."

# Update system
dnf update -y

# Install development tools
dnf groupinstall -y "Development Tools"
dnf install -y gcc gcc-c++ make automake autoconf libtool binutils binutils-devel

echo "=== Repairing ldconfig and rebuilding shared libraries cache... ==="
ldconfig
/sbin/ldconfig -v

# Add common library paths if missing
LIB_PATH_CONF="/etc/ld.so.conf.d/custom_libs.conf"
if [ ! -f "$LIB_PATH_CONF" ]; then
  echo "/usr/local/lib" > $LIB_PATH_CONF
  echo "/usr/lib64" >> $LIB_PATH_CONF
  ldconfig
fi

echo "=== Installing PHP build dependencies... ==="
dnf install -y libxml2-devel bzip2 bzip2-devel curl-devel libjpeg-devel libpng-devel libXpm-devel freetype-devel gmp-devel mariadb-devel aspell-devel recode-devel libicu-devel oniguruma-devel sqlite-devel libxslt-devel zip unzip

# Check and fix libmcrypt if needed
if ! rpm -q libmcrypt-devel &>/dev/null; then
  echo "Installing libmcrypt from source..."
  cd /usr/local/src
  wget -O mcrypt.tar.gz https://pecl.php.net/get/mcrypt
  tar -xzf mcrypt.tar.gz
  cd mcrypt*
  phpize
  ./configure && make && make install
fi

echo "=== Cleaning old PHP build directories... ==="
cd /usr/local/src
rm -rf php*

echo "=== Recompiling PHP via CWP... ==="
/scripts/php-selector recompile 8.1

echo "=== Fixing ld if corrupted... ==="
dnf reinstall -y binutils
ln -sf /usr/bin/ld.bfd /usr/bin/ld

echo "=== PHP Auto-Fix Completed! ==="
echo "You may now verify your PHP installation with: php -v"
