#!/bin/bash
# Script to perform a full uninstall of BI Catalog:
# Removes system service, CLI symlink, installation files,
# AND application-specific user data.

# Exit immediately if a command exits with a non-zero status.
set -e

# --- Configuration ---
APP_NAME="BI Catalog" # Used for display messages
SERVICE_NAME='bicatalogui'
CLI_COMMAND_NAME='bicatalog'
# For full uninstall, user-specific directories
USER_DATA_DIR_RELATIVE=".${CLI_COMMAND_NAME}" # e.g., $HOME/.bicatalog
USER_CONFIG_DIR_RELATIVE=".config/${CLI_COMMAND_NAME}" # e.g., $HOME/.config/bicatalog
TEMP_DATA_DIR_SYSTEM="/tmp/${CLI_COMMAND_NAME}" # e.g., /tmp/bicatalog
# Marker file to help identify the installation directory (recommended for your installer to create)
INSTALL_MARKER_FILE=".${CLI_COMMAND_NAME}_install_marker" # e.g., .bicatalog_install_marker

echo "Starting ${APP_NAME} full uninstallation..."
echo "(This will remove application-specific user data)"
echo "--------------------------------------------------"

# --- Sudo Handling ---
SUDO_CMD=''
# Check if running as root
if [ "$(id -u)" != "0" ]; then
    SUDO_CMD='sudo'
    echo "This script requires superuser access for some operations."
    echo "Attempting to run relevant commands with sudo."
    if command -v sudo >/dev/null 2>&1; then
        sudo -k # Invalidate timestamp
        if ! sudo -v; then
            echo "Sudo authentication failed. Please run this script as root or with sudo privileges."
            exit 1
        fi
    else
        echo "sudo command not found. Please run this script as root."
        exit 1
    fi
fi

# --- Determine Original User's Home Directory (for full uninstall) ---
INVOKING_USER_HOME_DIR=""
if [ -n "$SUDO_USER" ]; then
    INVOKING_USER_HOME_DIR=$(getent passwd "$SUDO_USER" | cut -d: -f6)
elif [ "$(id -u)" -eq 0 ]; then
    CURRENT_LOGIN_USER=$(logname 2>/dev/null)
    if [ -n "$CURRENT_LOGIN_USER" ] && [ "$CURRENT_LOGIN_USER" != "root" ]; then
        INVOKING_USER_HOME_DIR=$(getent passwd "$CURRENT_LOGIN_USER" | cut -d: -f6)
    else
        echo "Warning: Running directly as root. For full uninstall, user-specific data in a non-root user's home directory might not be targeted unless SUDO_USER was available."
        echo "If you intend to remove data for a specific user, ensure this script is invoked via 'sudo ./uninstall_full.sh' by that user, or remove data manually."
    fi
else
    INVOKING_USER_HOME_DIR="$HOME"
fi

if [ -z "$INVOKING_USER_HOME_DIR" ]; then
    echo "Caution: Could not reliably determine the original user's home directory."
    echo "Removal of data from user's home directory (e.g., ~/.${CLI_COMMAND_NAME}, ~/.config/${CLI_COMMAND_NAME}) will be skipped."
elif [ -n "$INVOKING_USER_HOME_DIR" ]; then # Only print if successfully determined
    echo "For full uninstall, will target user-specific data in: $INVOKING_USER_HOME_DIR (if it exists)"
fi
echo "--------------------------------------------------"


# Use a heredoc for the main logic to be executed with sudo if needed.
$SUDO_CMD bash <<EOF_INNER_SCRIPT
# Exit immediately if a command exits with a non-zero status (for the subshell)
set -e

echo "Running privileged uninstallation tasks..."
echo "--------------------------------------------------"

# --- Constants for inner script (escape \$ for deferred expansion) ---
SERVICE_NAME_INNER='${SERVICE_NAME}'
CLI_COMMAND_NAME_INNER='${CLI_COMMAND_NAME}'
INSTALL_MARKER_FILE_INNER='${INSTALL_MARKER_FILE}'
APP_NAME_INNER='${APP_NAME}'

# --- Variables passed from outer script (already expanded) ---
# These are available directly: INVOKING_USER_HOME_DIR, USER_DATA_DIR_RELATIVE,
# USER_CONFIG_DIR_RELATIVE, TEMP_DATA_DIR_SYSTEM.

# ------------------------------- Remove System Service -------------------------------
SERVICE_FILE_PATH="/etc/systemd/system/\${SERVICE_NAME_INNER}.service"

echo "Attempting to stop and remove system service: \${SERVICE_NAME_INNER}..."

if systemctl is-active --quiet "\${SERVICE_NAME_INNER}.service"; then
    echo "Stopping service: \${SERVICE_NAME_INNER}..."
    systemctl stop "\${SERVICE_NAME_INNER}.service" || echo "Warning: Failed to stop service."
else
    echo "Service \${SERVICE_NAME_INNER} is not active."
fi

if systemctl is-enabled --quiet "\${SERVICE_NAME_INNER}.service"; then
    echo "Disabling service: \${SERVICE_NAME_INNER}..."
    systemctl disable "\${SERVICE_NAME_INNER}.service" || echo "Warning: Failed to disable service."
else
    echo "Service \${SERVICE_NAME_INNER} is not enabled."
fi

if [ -f "\$SERVICE_FILE_PATH" ]; then
    echo "Removing service file: \$SERVICE_FILE_PATH..."
    rm -f "\$SERVICE_FILE_PATH"
    echo "Reloading systemd daemon..."
    systemctl daemon-reload
else
    echo "Service file \$SERVICE_FILE_PATH not found."
fi

echo "Resetting failed systemd units (if any)..."
systemctl reset-failed >/dev/null 2>&1 || true

echo "Service \${SERVICE_NAME_INNER} removal process finished."
echo "--------------------------------------------------"
echo ""

# ------------------------------- Remove CLI Installation -------------------------------
echo "Attempting to remove \${CLI_COMMAND_NAME_INNER} CLI..."
echo "--------------------------------------------------"

ACTUAL_CLI_CMD_PATH=""
if command -v "\${CLI_COMMAND_NAME_INNER}" >/dev/null 2>&1; then
    ACTUAL_CLI_CMD_PATH=\$(command -v "\${CLI_COMMAND_NAME_INNER}")
    echo "Found '\${CLI_COMMAND_NAME_INNER}' command at: \$ACTUAL_CLI_CMD_PATH"
else
    echo "\${CLI_COMMAND_NAME_INNER} command not found in PATH."
    echo "Uninstallation of CLI components skipped."
    ACTUAL_CLI_CMD_PATH=""
fi

INSTALLATION_DIR_TO_REMOVE=""

if [ -n "\$ACTUAL_CLI_CMD_PATH" ]; then
    SYMLINK_TARGET_PATH=""

    if [ -L "\$ACTUAL_CLI_CMD_PATH" ]; then
        echo "'\${CLI_COMMAND_NAME_INNER}' command at '\$ACTUAL_CLI_CMD_PATH' is a symlink."
        SYMLINK_TARGET_PATH=\$(readlink -f "\$ACTUAL_CLI_CMD_PATH")
        echo "Symlink target: '\$SYMLINK_TARGET_PATH'"

        if [ -n "\$SYMLINK_TARGET_PATH" ] && [ -e "\$SYMLINK_TARGET_PATH" ]; then
            TARGET_PARENT_DIR=\$(dirname "\$SYMLINK_TARGET_PATH")
            if [ "\$(basename "\$TARGET_PARENT_DIR")" == "bin" ] && \
               [ "\$TARGET_PARENT_DIR" != "/bin" ] && [ "\$TARGET_PARENT_DIR" != "/usr/bin" ] && \
               [ "\$TARGET_PARENT_DIR" != "/sbin" ] && [ "\$TARGET_PARENT_DIR" != "/usr/sbin" ]; then
                INSTALLATION_DIR_TO_REMOVE=\$(dirname "\$TARGET_PARENT_DIR")
            else
                INSTALLATION_DIR_TO_REMOVE="\$TARGET_PARENT_DIR"
            fi
            echo "Deduced potential installation directory from symlink: '\$INSTALLATION_DIR_TO_REMOVE'"
        else
            echo "Warning: Symlink target '\$SYMLINK_TARGET_PATH' for '\$ACTUAL_CLI_CMD_PATH' is empty or the target does not exist."
        fi
        echo "Removing symlink: \$ACTUAL_CLI_CMD_PATH..."
        rm -f "\$ACTUAL_CLI_CMD_PATH"
        echo "Symlink '\$ACTUAL_CLI_CMD_PATH' removed."

    elif [ -f "\$ACTUAL_CLI_CMD_PATH" ]; then
        echo "'\${CLI_COMMAND_NAME_INNER}' command at '\$ACTUAL_CLI_CMD_PATH' is a direct file."
        INSTALLATION_DIR_TO_REMOVE=\$(dirname "\$ACTUAL_CLI_CMD_PATH")
        echo "Deduced potential installation directory from direct file: '\$INSTALLATION_DIR_TO_REMOVE'"
        echo "Removing direct file: \$ACTUAL_CLI_CMD_PATH..."
        rm -f "\$ACTUAL_CLI_CMD_PATH"
        echo "File '\$ACTUAL_CLI_CMD_PATH' removed."
    else
        echo "Warning: '\${CLI_COMMAND_NAME_INNER}' path '\$ACTUAL_CLI_CMD_PATH' is not a symlink or regular file."
    fi

    if [ -n "\$INSTALLATION_DIR_TO_REMOVE" ]; then
        # SAFETY CHECKS for installation directory
        if [ -d "\$INSTALLATION_DIR_TO_REMOVE" ] && \
           [ "\$INSTALLATION_DIR_TO_REMOVE" != "/" ] && \
           [ "\$INSTALLATION_DIR_TO_REMOVE" != "/bin" ] && [ "\$INSTALLATION_DIR_TO_REMOVE" != "/sbin" ] && \
           [ "\$INSTALLATION_DIR_TO_REMOVE" != "/usr" ] && [ "\$INSTALLATION_DIR_TO_REMOVE" != "/lib" ] && \
           [ "\$INSTALLATION_DIR_TO_REMOVE" != "/lib64" ] && [ "\$INSTALLATION_DIR_TO_REMOVE" != "/etc" ] && \
           [ "\$INSTALLATION_DIR_TO_REMOVE" != "/opt" ] && [ "\$INSTALLATION_DIR_TO_REMOVE" != "/var" ] && \
           [ "\$INSTALLATION_DIR_TO_REMOVE" != "/srv" ] && [ "\$INSTALLATION_DIR_TO_REMOVE" != "/tmp" ] && \
           [ "\$INSTALLATION_DIR_TO_REMOVE" != "${INVOKING_USER_HOME_DIR}" ] && \
           ( [[ "\$(basename "\$INSTALLATION_DIR_TO_REMOVE")" == *"\${CLI_COMMAND_NAME_INNER}"* ]] || \
             [[ "\$(basename "\$INSTALLATION_DIR_TO_REMOVE")" == *"\${APP_NAME_INNER}"* ]] || \
             [ -f "\$INSTALLATION_DIR_TO_REMOVE/\${INSTALL_MARKER_FILE_INNER}" ] ); then

            echo "Safety checks passed for directory: '\$INSTALLATION_DIR_TO_REMOVE'"
            echo "Deleting installation directory: \$INSTALLATION_DIR_TO_REMOVE..."
            rm -rf "\$INSTALLATION_DIR_TO_REMOVE"
            echo "Directory '\$INSTALLATION_DIR_TO_REMOVE' removed."
        elif [ -d "\$INSTALLATION_DIR_TO_REMOVE" ]; then
            echo "SAFETY WARNING: Directory '\$INSTALLATION_DIR_TO_REMOVE' was identified."
            echo "However, it did NOT pass strict safety criteria for automatic deletion."
            echo "Path '\$INSTALLATION_DIR_TO_REMOVE' will NOT be automatically deleted."
        else
            echo "Warning: Deduced installation directory '\$INSTALLATION_DIR_TO_REMOVE' does not exist or is not a directory."
        fi
    else
        echo "No primary installation directory identified for removal."
    fi
fi

echo "CLI uninstallation process finished."
echo "--------------------------------------------------"
echo ""

# ------------------------------- Remove Application Specific Data (full uninstall) -------------------------------
echo "Performing full uninstall: Removing application-specific data..."

# Data in user's home
if [ -n "${INVOKING_USER_HOME_DIR}" ]; then
    # \$HOME/.bicatalog
    APP_DATA_DIR_USER_HOME="${INVOKING_USER_HOME_DIR}/${USER_DATA_DIR_RELATIVE}"
    if [ -d "\$APP_DATA_DIR_USER_HOME" ]; then # Escaped for inner shell
        echo "Removing user data directory: \$APP_DATA_DIR_USER_HOME"
        rm -rf "\$APP_DATA_DIR_USER_HOME"
    else
        echo "User data directory not found (or already removed): \$APP_DATA_DIR_USER_HOME"
    fi

    # \$HOME/.config/bicatalog
    APP_CONFIG_DIR_USER_HOME="${INVOKING_USER_HOME_DIR}/${USER_CONFIG_DIR_RELATIVE}"
    if [ -d "\$APP_CONFIG_DIR_USER_HOME" ]; then # Escaped for inner shell
        echo "Removing user config directory: \$APP_CONFIG_DIR_USER_HOME"
        rm -rf "\$APP_CONFIG_DIR_USER_HOME"
    else
        echo "User config directory not found (or already removed): \$APP_CONFIG_DIR_USER_HOME"
    fi
else
    echo "Skipping removal of data from user's home directory as the original user's home could not be reliably determined or was not set."
fi

# Data in /tmp
# TEMP_DATA_DIR_SYSTEM is already expanded from outer script
if [ -d "${TEMP_DATA_DIR_SYSTEM}" ]; then
    echo "Removing temporary data directory: ${TEMP_DATA_DIR_SYSTEM}"
    rm -rf "${TEMP_DATA_DIR_SYSTEM}"
else
    echo "Temporary data directory not found (or already removed): ${TEMP_DATA_DIR_SYSTEM}"
fi
echo "Application-specific data removal finished."
echo "--------------------------------------------------"
echo ""

echo "\${APP_NAME_INNER} full uninstallation complete."
echo "(Application-specific user data has been removed)"
EOF_INNER_SCRIPT

exit 0
