#!/usr/bin/env bash

######### Let's support alpine installations
PATH=${PATH}:/usr/local/bin

################################################################################
############################ GLOBAL VARIABLES ##################################
################################################################################
####### IMPORTANT: PHP_AGENT_DIR is needed otherwise fpm will fail when generating
#######            the apk distribution with an Invalid tar stream error.
PHP_AGENT_DIR=/opt/elastic/elastic-otel-php
BACKUP_EXTENSION=".agent.uninstall.bck"
CUSTOM_INI_FILE_NAME="elastic-otel-custom.ini"
ELASTIC_INI_FILE_NAME="elastic-otel.ini"

################################################################################
########################## FUNCTION CALLS BELOW ################################
################################################################################

################################################################################
#### Function php_command ######################################################
function php_command() {
    PHP_BIN=$(command -v php)
    ${PHP_BIN} -d memory_limit=128M "$@"
}

################################################################################
#### Function php_ini_file_path ################################################
function php_ini_file_path() {
    php_command -i \
        | grep 'Configuration File (php.ini) Path =>' \
        | sed -e 's#Configuration File (php.ini) Path =>##g' \
        | head -n 1 \
        | awk '{print $1}'
}

################################################################################
#### Function php_config_d_path ################################################
function php_config_d_path() {
    php_command -i \
        | grep 'Scan this dir for additional .ini files =>' \
        | sed -e 's#Scan this dir for additional .ini files =>##g' \
        | head -n 1 \
        | awk '{print $1}'
}

################################################################################
#### Function is_extension_enabled #############################################
function is_extension_enabled() {
    php_command -m | grep -q 'elastic'
}

################################################################################
#### Function remove_extension_configuration_to_file ###########################
function remove_extension_configuration_to_file() {
    # remove lines from ; THIS IS AN AUTO-GENERATED FILE by the Elastic Distribution for OpenTelemetry PHP post-install.sh script
    # with elastic_otel.bootstrap_php_part_file=.+
    # then ; END OF AUTO-GENERATED by the Elastic Distribution for OpenTelemetry PHP post-install.sh script
    HEADER='; THIS IS AN AUTO-GENERATED FILE by the Elastic Distribution for OpenTelemetry PHP post-install.sh'
    FOOTER='; END OF AUTO-GENERATED by the Elastic Distribution for OpenTelemetry PHP post-install.sh'
    EXTENSION='extension=.*'
    BOOTSTRAP='elastic_otel.bootstrap_php_part_file=.*'
    numberOfHeaderMatches=$(grep "${HEADER}" "$1" -c)
    numberOfExtensionMatches=$(grep "${EXTENSION}" "$1" -c)
    numberOfBootstrapMatches=$(grep "${BOOTSTRAP}" "$1" -c)
    numberOfFooterMatches=$(grep "${FOOTER}" "$1" -c)
    ## Delete only if there is only an automated installation in place.
    if [ "${numberOfHeaderMatches}" == "1" ] && [ "${numberOfExtensionMatches}" == "1" ] && [ "${numberOfBootstrapMatches}" == "1" ] && [ "${numberOfFooterMatches}" == "1" ] ; then
        TMP_FILE=/tmp/uninstall-apm-agent-pipeline
        grep "${HEADER}" "$1" -A 3 > ${TMP_FILE}
        footer=$(grep "${FOOTER}" -n ${TMP_FILE} | cut -f1 -d:)
        extension=$(grep "${EXTENSION}" -n ${TMP_FILE} | cut -f1 -d:)
        bootstrap=$(grep "${BOOTSTRAP}" -n ${TMP_FILE} | cut -f1 -d:)
        ## Ensure the automated installation in place uses the right format.
        if [ "${extension}" == "2" ] && [ "${bootstrap}" == "3" ] && [ "${footer}" == "4" ] ; then
            echo "$1 has been configured with the Elastic Distribution for OpenTelemetry PHP setup, let's uninstalled it."
            headerLine=$(grep "${HEADER}" -n "$1" | cut -f1 -d:)
            extensionLine=$((headerLine + 1))
            bootstrapLine=$((headerLine + 2))
            footerLine=$((headerLine + 3))
            sed -i${BACKUP_EXTENSION} "${headerLine}d;${extensionLine}d;${bootstrapLine}d;${footerLine}d" "$1"
        else
            echo "$1 has been configured with the Elastic Distribution for OpenTelemetry PHP setup. But it cannot be uninstalled automatically."
            manual_extension_agent_uninstallation
        fi
    else
        echo "$1 has been configured with the Elastic Distribution for OpenTelemetry PHP setup. But it cannot be uninstalled automatically."
        manual_extension_agent_uninstallation
    fi
}

################################################################################
#### Function manual_extension_agent_uninstallation ############################
function manual_extension_agent_uninstallation() {
    echo 'Uninstall the Agent manually as explained in:'
    echo 'https://github.com/elastic/apm-agent-php/blob/main/docs/setup.asciidoc'
}

################################################################################
#### Function uninstall_conf_d_files ###########=###############################
function uninstall_conf_d_files() {
    PHP_CONFIG_D_PATH=$1

    echo "Uninstalling ${ELASTIC_INI_FILE_NAME} for supported SAPI's"

    # Detect installed SAPI's
    SAPI_DIR=${PHP_CONFIG_D_PATH%/*/conf.d}/
    SAPI_CONFIG_DIRS=()
    if [ "${PHP_CONFIG_D_PATH}" != "${SAPI_DIR}" ]; then
        # CLI
        CLI_CONF_D_PATH="${SAPI_DIR}cli/conf.d"
        if [ -d "${CLI_CONF_D_PATH}" ]; then
            SAPI_CONFIG_DIRS+=("${CLI_CONF_D_PATH}")
        fi
        # Apache
        APACHE_CONF_D_PATH="${SAPI_DIR}apache2/conf.d"
        if [ -d "${APACHE_CONF_D_PATH}" ]; then
            SAPI_CONFIG_DIRS+=("${APACHE_CONF_D_PATH}")
        fi
        ## FPM
        FPM_CONF_D_PATH="${SAPI_DIR}fpm/conf.d"
        if [ -d "${FPM_CONF_D_PATH}" ]; then
            SAPI_CONFIG_DIRS+=("${FPM_CONF_D_PATH}")
        fi
    fi

    if [ ${#SAPI_CONFIG_DIRS[@]} -eq 0 ]; then
        SAPI_CONFIG_DIRS+=("$PHP_CONFIG_D_PATH")
    fi

    for SAPI_CONFIG_D_PATH in "${SAPI_CONFIG_DIRS[@]}" ; do
        echo "Found SAPI config directory: ${SAPI_CONFIG_D_PATH}"
        unlink_file "${SAPI_CONFIG_D_PATH}/98-${ELASTIC_INI_FILE_NAME}"
        unlink_file "${SAPI_CONFIG_D_PATH}/99-${CUSTOM_INI_FILE_NAME}"
    done
}

################################################################################
#### Function unlink_file ######################################################
function unlink_file() {
    echo "Removing ${1}"
    test -L "${1}" && unlink "${1}"
}

################################################################################
############################### MAIN ###########################################
################################################################################
echo 'Uninstalling Elastic Distribution for OpenTelemetry PHP'
PHP_INI_FILE_PATH="$(php_ini_file_path)/php.ini"
PHP_CONFIG_D_PATH="$(php_config_d_path)"

echo "DEBUG: before-remove parameter is '$1'"
if [ "$1" = "1" ]; then
    echo "The action is an upgrade in RPM, therefore this is not required"
    exit 0
fi

if [ -e "${PHP_CONFIG_D_PATH}" ]; then
    uninstall_conf_d_files "${PHP_CONFIG_D_PATH}"
fi
if [ -e "${PHP_INI_FILE_PATH}" ] ; then
    if grep -q "elastic_otel_php_loader.so" "${PHP_INI_FILE_PATH}" ; then
        remove_extension_configuration_to_file "${PHP_INI_FILE_PATH}"
    else
        echo '  extension configuration does not exist for the Elastic Distribution for OpenTelemetry PHP.'
        echo '  skipping ... '
    fi
else
    echo 'No default php.ini file has been found.'
fi

if is_extension_enabled ; then
    echo 'Failed. Elastic Distribution for OpenTelemetry PHP extension is still enabled.'
    if [ -e "${PHP_INI_FILE_PATH}${BACKUP_EXTENSION}" ] ; then
        echo "Reverted changes in the file ${PHP_INI_FILE_PATH}"
        mv -f "${PHP_INI_FILE_PATH}${BACKUP_EXTENSION}" "${PHP_INI_FILE_PATH}"
        echo "${PHP_INI_FILE_PATH} got some leftovers please delete the entries for the Elastic Distribution for OpenTelemetry PHP manually"
    fi
else
    echo 'Extension has been removed successfully for Elastic Distribution for OpenTelemetry PHP.'
fi
