#!/bin/bash
#
# whatap-infra tarball uninstaller
# Supports: CentOS/RHEL 7+, Ubuntu 16.04+, Debian 9+, SUSE 12+, Amazon Linux 2+
#
# Usage: ./uninstall.sh [--prefix /custom/path]
#
# Default prefix: /usr/whatap/infra
#

set -e

META_DIR="/etc/whatap"
META_FILE="${META_DIR}/infra.meta"
PREFIX=""
PREFIX_EXPLICIT=false

# Safe meta file parser — reads only allowed keys, no source/eval
read_meta() {
    local file="$1"
    if [ ! -f "$file" ]; then
        return 1
    fi
    local file_owner
    file_owner=$(stat -c '%u' "$file" 2>/dev/null || echo "unknown")
    if [ "$file_owner" != "0" ]; then
        echo "  WARNING: Meta file $file is not owned by root (uid=$file_owner), ignoring"
        return 1
    fi
    META_INSTALL_PREFIX=$(grep '^INSTALL_PREFIX=' "$file" 2>/dev/null | head -1 | cut -d'=' -f2- | tr -d '"' | tr -d "'")
    META_INSTALL_VERSION=$(grep '^INSTALL_VERSION=' "$file" 2>/dev/null | head -1 | cut -d'=' -f2- | tr -d '"' | tr -d "'")
    case "$META_INSTALL_PREFIX" in
        /*) ;; # OK
        *)
            echo "  WARNING: Invalid INSTALL_PREFIX in meta file, ignoring"
            META_INSTALL_PREFIX=""
            return 1
            ;;
    esac
    return 0
}

print_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  --prefix PATH    Installation directory (auto-detected from meta if omitted)"
    echo "  --help           Show this help message"
}

while [ $# -gt 0 ]; do
    case "$1" in
        --prefix)
            PREFIX="$2"
            PREFIX_EXPLICIT=true
            shift 2
            ;;
        --help)
            print_usage
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            print_usage
            exit 1
            ;;
    esac
done

# Check root
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: This script must be run as root"
    exit 1
fi

# Determine PREFIX from meta or --prefix
if [ "$PREFIX_EXPLICIT" = true ]; then
    PREFIX="${PREFIX%/}"
elif read_meta "$META_FILE"; then
    PREFIX="${META_INSTALL_PREFIX}"
    echo "  Using install path from meta: $PREFIX"
else
    echo "Error: No meta file found at $META_FILE and --prefix not specified."
    echo "  Please specify: $0 --prefix /path/to/whatap/infra"
    exit 1
fi

echo "=== whatap-infra uninstaller ==="
echo "Uninstall prefix: $PREFIX"
if [ -n "$META_INSTALL_VERSION" ]; then
    echo "Installed version: $META_INSTALL_VERSION"
fi
echo ""

# Verify installation exists
if [ ! -f "$PREFIX/whatap_infrad" ]; then
    echo "Error: whatap-infra not found at $PREFIX"
    exit 1
fi

# Stop and remove whatap-infra service (both types)
echo "[1/4] Stopping services..."

# systemd cleanup
if [ -f /etc/systemd/system/whatap-infra.service ]; then
    systemctl stop whatap-infra 2>/dev/null || true
    systemctl disable whatap-infra 2>/dev/null || true
    rm -f /etc/systemd/system/whatap-infra.service
    systemctl daemon-reload 2>/dev/null || true
    echo "  - systemd service removed"
fi

# SysV init cleanup
if [ -f /etc/init.d/whatap-infra ]; then
    if [ "$(cat /proc/1/comm 2>/dev/null)" != "systemd" ]; then
        service whatap-infra stop 2>/dev/null || true
    fi
    if command -v chkconfig >/dev/null 2>&1; then
        chkconfig whatap-infra off 2>/dev/null || true
        chkconfig --del whatap-infra 2>/dev/null || true
    elif command -v update-rc.d >/dev/null 2>&1; then
        update-rc.d -f whatap-infra remove 2>/dev/null || true
    fi
    rm -f /etc/init.d/whatap-infra
    echo "  - SysV init script removed"
fi

# Stop and remove updater (both types)
echo "[2/4] Stopping updater..."

if [ -f /etc/systemd/system/whatap-updater.service ]; then
    systemctl stop whatap-updater 2>/dev/null || true
    systemctl disable whatap-updater 2>/dev/null || true
    rm -f /etc/systemd/system/whatap-updater.service
    systemctl daemon-reload 2>/dev/null || true
    echo "  - updater systemd service removed"
fi

if [ -f /etc/init.d/whatap-updater ]; then
    if [ "$(cat /proc/1/comm 2>/dev/null)" != "systemd" ]; then
        service whatap-updater stop 2>/dev/null || true
    fi
    if command -v chkconfig >/dev/null 2>&1; then
        chkconfig --del whatap-updater 2>/dev/null || true
    elif command -v update-rc.d >/dev/null 2>&1; then
        update-rc.d -f whatap-updater remove 2>/dev/null || true
    fi
    rm -f /etc/init.d/whatap-updater
    echo "  - updater init script removed"
fi
rm -f /var/run/whatap-updater.pid
rm -f /var/log/whatap-updater.log

# Remove files
echo "[3/4] Removing files..."
rm -f "$PREFIX/whatap_infrad"
rm -f "$PREFIX/infra_agent_patch.sh"
rm -f "$PREFIX/ChangeLog.txt"
rm -f "$PREFIX/.install_prefix"
rm -f "$PREFIX/conf/VERSION"
rm -f "$PREFIX/conf/whatap_infrad.pid"
rm -f "$PREFIX"/*.pid

# Ask about config
if [ -f "$PREFIX/conf/whatap.conf" ]; then
    echo ""
    echo "  WARNING: $PREFIX/conf/whatap.conf still exists."
    echo "  Remove it manually if no longer needed:"
    echo "    rm -rf $PREFIX"
    echo ""
else
    # Remove empty directories
    rmdir "$PREFIX/conf" 2>/dev/null || true
    rmdir "$PREFIX" 2>/dev/null || true
fi

# Remove meta file
echo "[4/4] Cleaning up meta information..."
rm -f "$META_FILE"
echo "  - Meta file removed"
rmdir "$META_DIR" 2>/dev/null || true

echo ""
echo "Uninstallation complete!"
echo ""
