#!/usr/bin/env bash
# gniza4cp uninstall script

set -euo pipefail

INSTALL_DIR="/usr/local/gniza4cp"
BIN_LINK="/usr/local/bin/gniza4cp"

if [[ $EUID -ne 0 ]]; then
    echo "Error: uninstall.sh must be run as root" >&2
    exit 1
fi

echo "Uninstalling gniza4cp..."

# Remove symlink
if [[ -L "$BIN_LINK" ]]; then
    rm -f "$BIN_LINK"
    echo "Removed $BIN_LINK"
fi

# Remove install directory
if [[ -d "$INSTALL_DIR" ]]; then
    rm -rf "$INSTALL_DIR"
    echo "Removed $INSTALL_DIR"
fi

# ── Remove cron entries ───────────────────────────────────────
if crontab -l 2>/dev/null | grep -q '# gniza4cp:'; then
    echo "Removing gniza4cp cron entries..."
    crontab -l 2>/dev/null | grep -v '# gniza4cp:' | grep -v '/usr/local/bin/gniza4cp' | crontab -
    echo "Cron entries removed."
fi

# ── WHM Plugin ────────────────────────────────────────────────
WHM_CGI_DIR="/usr/local/cpanel/whostmgr/docroot/cgi"
if [[ -d "$WHM_CGI_DIR/gniza4cp-whm" ]]; then
    echo "Removing WHM plugin..."
    /usr/local/cpanel/bin/unregister_appconfig gniza4cp-whm 2>/dev/null || true
    rm -rf "$WHM_CGI_DIR/gniza4cp-whm"
    echo "WHM plugin removed."
fi

# ── cPanel User Plugin ────────────────────────────────────────
CPANEL_BASE="/usr/local/cpanel/base/frontend/jupiter"
ADMINBIN_DIR="/usr/local/cpanel/bin/admin/Gniza4cp"
if [[ -d "$CPANEL_BASE/gniza4cp" ]]; then
    echo "Removing cPanel user plugin..."
    # uninstall_plugin expects a tar.gz archive with install.json + icon
    if [[ -f "$CPANEL_BASE/gniza4cp/install.json" ]]; then
        PLUGIN_TMPDIR="$(mktemp -d)"
        mkdir -p "$PLUGIN_TMPDIR/gniza4cp/assets"
        cp "$CPANEL_BASE/gniza4cp/install.json" "$PLUGIN_TMPDIR/"
        cp "$CPANEL_BASE/gniza4cp/assets/gniza4cp-cpanel-icon.png" "$PLUGIN_TMPDIR/gniza4cp/assets/" 2>/dev/null || true
        tar -czf "$PLUGIN_TMPDIR/gniza4cp-cpanel.tar.gz" -C "$PLUGIN_TMPDIR" install.json gniza4cp/assets/gniza4cp-cpanel-icon.png 2>/dev/null || \
        tar -czf "$PLUGIN_TMPDIR/gniza4cp-cpanel.tar.gz" -C "$PLUGIN_TMPDIR" install.json
        /usr/local/cpanel/scripts/uninstall_plugin "$PLUGIN_TMPDIR/gniza4cp-cpanel.tar.gz" 2>/dev/null || true
        rm -rf "$PLUGIN_TMPDIR"
    fi
    rm -rf "$CPANEL_BASE/gniza4cp"
    echo "cPanel user plugin removed."
fi
if [[ -d "$ADMINBIN_DIR" ]]; then
    rm -rf "$ADMINBIN_DIR"
    echo "AdminBin module removed."
fi

echo ""
echo "gniza4cp uninstalled."
echo ""
echo "The following were NOT removed (manual cleanup if desired):"
echo "  /etc/gniza4cp/          (configuration + remotes.d/)"
echo "  /var/log/gniza4cp/      (log files)"
echo "  /var/run/gniza4cp.lock  (lock file)"
echo ""
echo "To remove configs:  rm -rf /etc/gniza4cp/"
echo "To remove logs:     rm -rf /var/log/gniza4cp/"
