#!/usr/bin/env bash

uid=$(id -u)
if [ "$uid" != "0" ]; then
    echo "Command must be executed as privileged user"
    exit 0
fi
case "$1" in
install)
    echo "Try to find php-selector for hestiacp"
    update-alternatives --display php | grep hestiacp-php-selector
    if [ $? -ne 0 ]; then
        echo "Register php-selector"
        update-alternatives --install /usr/bin/php php /usr/bin/hestiacp-php-selector 1
        if [ ! -e /etc/hestia_php_selector/system/php.path ]; then
            mkdir -p /etc/hestia_php_selector/system/
            current_path_to_php=$(readlink -f /usr/bin/php)
            echo "$current_path_to_php" > /etc/hestia_php_selector/system/php.path
            chmod 644 /etc/hestia_php_selector/system/php.path
        fi
        /usr/bin/hestiacp-php-admin add
    fi
;;
delete)
    if [ -e /etc/hestia_php_selector/system/php.path ]; then
        php_sys=$(cat /etc/hestia_php_selector/system/php.path)
        if [ -n "$php_sys" ]; then
            update-alternatives --set php "$php_sys"
        fi
    fi
    update-alternatives --display php | grep hestiacp-php-selector
    if [ $? -ne 0 ]; then
        update-alternatives --remove php /usr/bin/hestiacp-php-selector
    fi
    /usr/bin/hestiacp-php-admin remove-all
;;
*)
    echo "Unknown command"
;;
esac