#!/usr/bin/env bash
##makedesc: Install php-spx

set -eo pipefail

installed() { command -v "$1" >/dev/null 2>&1; }

install() {
    if [ "$(uname -s)" = "Darwin" ]; then
        echo "ERROR: php-spx is not supported on macOS (requires Linux PHP extension build)." >&2
        exit 1
    fi

    echo
    echo "==============================================="
    echo "Installing php-spx"
    echo "==============================================="
    echo

    if ! installed php; then
        echo "ERROR: You need php to be installed" >&2
        exit 1
    fi
    if ! installed phpize; then
        echo "ERROR: You need php-dev to be installed" >&2
        exit 2
    fi
    if ! installed make; then
        sudo apt install -y make
    fi

    mkdir -p "$HOME/install/php-spx"
    if installed wget; then
        wget -q --show-progress https://github.com/NoiseByNorthwest/php-spx/archive/refs/heads/release/latest.zip -O /tmp/php-spx.zip
    else
        curl -fsSL https://github.com/NoiseByNorthwest/php-spx/archive/refs/heads/release/latest.zip -o /tmp/php-spx.zip
    fi
    unzip -oq /tmp/php-spx.zip -d "$HOME/install/php-spx"
    rm /tmp/php-spx.zip
    cd "$HOME/install/php-spx/php-spx-release-latest"
    phpize
    ./configure
    make
    sudo make install

    PHPVER=$(php -r 'echo ($v=explode(".",PHP_VERSION))[0].".".$v[1];')
    cat << EOF | sudo tee -a "/etc/php/${PHPVER}/mods-available/spx.ini"
; https://github.com/NoiseByNorthwest/php-spx/tree/release/latest#configuration
; https://habr.com/ru/post/505192/

; extension=spx.so
; spx.data_dir = '/tmp/spx'
spx.http_enabled = 0
spx.http_key = 'spx'
; spx.http_ip_whitelist = "127.0.0.1"

EOF

    sudo ln -sf "/etc/php/${PHPVER}/mods-available/spx.ini" "/etc/php/${PHPVER}/cli/conf.d/99-spx.ini"

    echo
    echo "Finish!"
    echo
}

case "$1" in
    *) install ;;
esac
