#!/bin/bash -e

. ./fusion-sys.cfg

# Was previous step completed?
if [ ! -f installed.basedir ]; then
    echo "Base directory structure was not completed" >&2
    exit 1
fi

# Is SourceGuardian already installed?
if [ -f installed.sourceguardian ]; then
    echo "SourceGuardian already installed - skipping..."
    exit 0
fi

# Get PHP version
phpver=$(php -v | head -n 1 | cut -d ' ' -f 2 | cut -d . -f 1,2)

ixedfile="ixed.$phpver.lin"
entry="extension=$ixedfile"

if [ "$arch" = "x86_64" ]; then
	zipfile="sg/loaders.linux-x86_64.zip"
else
	echo "Error: Cannot install on 32bit systems"
	exit 1
fi


# Make sure we are using the exact php extension dir
# NOTE: This cannot be done in init.sh since it requires php-dev to be installed
if [ `command -v php-config` ]; then
    php_extension_dir=$(php-config --extension-dir)
fi

# Extract SourceGuardian extension to the proper directory
unzip -o "$zipfile" "$ixedfile" -d "$php_extension_dir"

if [ -f "$php_extension_dir/$ixedfile" ]; then
    echo "Sourceguardian extension found for PHP version $phpver"
else
    echo "No valid Sourceguardian extension found for PHP version $phpver"
    exit 1
fi

if grep -q "$entry" "$phpini" "$phpconfd"/*; then
    echo "Sourceguardian extension already in php.ini"
else
    echo "Adding Sourceguardian extension to php.ini"
    echo "$entry" > "$phpconfd"/sourceguardian.ini

    # For Ubuntu/Debian also add it to the php cli conf.d
    if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
        echo "$entry" > "$phpconfdcli"/sourceguardian.ini
    fi
fi

service "$httpd" restart

# Restart php-fpm for el8 and el9
if [ "$dist" == "el8" ] || [ "$dist" == "el9" ]; then
    systemctl restart php-fpm
fi

echo "SourceGuardian installed OK"
touch installed.sourceguardian