#!/bin/bash

BASEDIR=$(dirname $(readlink -f $0))

. $BASEDIR/../../../../var/xi-sys.cfg

# Scheduled Backups dependencies
if [ "$distro" == "Debian" ] || [ "$distro" == "Ubuntu" ]; then
	phpver=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')

    # Ensure phpize/php-config point to the correct PHP version
    update-alternatives --set phpize /usr/bin/phpize${phpver} 2>/dev/null || true
    update-alternatives --set php-config /usr/bin/php-config${phpver} 2>/dev/null || true

    pecl uninstall ssh2
    sudo sed -i '/^extension=ssh2\.so$/d' $(find /etc/php -name "php.ini" | grep apache2)
    sudo sed -i '/^extension=ssh2\.so$/d' $(find /etc/php -name "php.ini" | grep cli)
    pecl config-set php_ini "$(php -r 'echo php_ini_loaded_file();')" 2>/dev/null || true
    printf "\n" | pecl install $proddir/html/includes/components/scheduledbackups/includes/ssh2-1.4.1.tgz || pecl list | grep -qi ssh2
    echo "extension=ssh2.so" | tee -a $(find /etc/php -name "php.ini" | grep apache2)
    echo "extension=ssh2.so" | tee -a $(find /etc/php -name "php.ini" | grep cli)

    # Also enable for CLI via mods-available
    echo "extension=ssh2.so" > "/etc/php/${phpver}/mods-available/ssh2.ini"
    phpenmod -v "${phpver}" ssh2 2>/dev/null || true
    systemctl restart apache2
else
    pecl uninstall ssh2
    sed -i 's/^extension=ssh2\.so/;extension=ssh2.so/' /etc/php.d/ssh2.ini
    pecl config-set php_ini "$(php -r 'echo php_ini_loaded_file();')" 2>/dev/null || true
    printf "\n" | pecl install $proddir/html/includes/components/scheduledbackups/includes/ssh2-1.4.1.tgz || pecl list | grep -qi ssh2
    echo "extension=ssh2.so" > /etc/php.d/ssh2.ini
    systemctl restart httpd php-fpm
fi

chown $nagiosuser:$nagiosgroup /store/backups/nagiosxi
exit 0
