#!/usr/bin/env bash
#sudo curl -sL https://bit.ly/multilarm-uninstall | bash
#sudo curl -sL https://bit.ly/multilarm-uninstall | bash -s -- --yes
set -euo pipefail

# ------------------------------------------------------------
# Parse flags
# ------------------------------------------------------------

AUTO_YES=false
for arg in "$@"; do
    case "$arg" in
        -y|--yes) AUTO_YES=true ;;
    esac
done

# When piped from curl, stdin is the script itself so interactive
# prompts cannot work. Detect this and enable auto-yes mode.
if [[ "$AUTO_YES" == false ]] && ! [ -t 0 ]; then
    echo "Non-interactive mode detected (e.g. curl | bash). Enabling --yes."
    echo "Optional items (config, Adhan, audio lib, lingering) will be KEPT."
    echo "Run the script locally with no flags for interactive prompts,"
    echo "or pass --yes to remove everything."
    echo ""
    AUTO_YES=false
    NON_INTERACTIVE=true
else
    NON_INTERACTIVE=false
fi

echo "==================== Multilarm Uninstaller ===================="

# Require root / sudo
if [[ $EUID -ne 0 ]]; then
    echo "Error: This script must be run with sudo."
    echo "Usage: sudo bash multilarmuninstall.sh"
    exit 1
fi

# Detect real user even when script is run with sudo
if [ -n "${SUDO_USER:-}" ]; then
    REAL_USER="$SUDO_USER"
else
    REAL_USER="$(whoami)"
fi

REAL_HOME=$(eval echo "~$REAL_USER")
USER_UID=$(id -u "$REAL_USER")
XDG_RUNTIME_DIR="/run/user/$USER_UID"

echo "Uninstalling for user: $REAL_USER"
echo "Home directory: $REAL_HOME"

# ------------------------------------------------------------
# Helper: ask yes/no
# In --yes mode, always returns 0 (yes).
# In non-interactive pipe mode (no --yes), always returns 1
# (no) to safely skip optional destructive items.
# In interactive mode, prompts the user (defaults to yes).
# ------------------------------------------------------------

ask_yes_no() {
    local prompt="$1"
    if [[ "$AUTO_YES" == true ]]; then
        echo "$prompt [Y/n]: y (auto)"
        return 0
    fi
    if [[ "$NON_INTERACTIVE" == true ]]; then
        echo "$prompt [Y/n]: n (non-interactive, skipped)"
        return 1
    fi
    local answer
    read -r -p "$prompt [Y/n]: " answer </dev/tty
    case "${answer,,}" in
        n|no) return 1 ;;
        *) return 0 ;;
    esac
}

# ------------------------------------------------------------
# Stop and disable systemd user service
# ------------------------------------------------------------

echo ""
echo "--- Stopping Multilarm service ---"

if [[ -f "$REAL_HOME/.config/systemd/user/multilarm.service" ]]; then
    sudo -u "$REAL_USER" env XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" \
        systemctl --user stop multilarm.service 2>/dev/null || true

    sudo -u "$REAL_USER" env XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" \
        systemctl --user disable multilarm.service 2>/dev/null || true

    rm -f "$REAL_HOME/.config/systemd/user/multilarm.service"

    sudo -u "$REAL_USER" env XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" \
        systemctl --user daemon-reload 2>/dev/null || true

    echo "Service stopped, disabled, and removed."
else
    echo "Service file not found, skipping."
fi

# ------------------------------------------------------------
# Remove CPU governor service (idempotent — present only on Pi-class
# installs since 2026-05-18; harmless elsewhere). Always remove without
# prompting so an uninstall fully reverts the host to its default
# (typically "ondemand") governor on next reboot.
# ------------------------------------------------------------

if [[ -f /etc/systemd/system/multilarm-cpu-governor.service ]]; then
    echo ""
    echo "--- Removing CPU governor service ---"
    systemctl stop    multilarm-cpu-governor.service 2>/dev/null || true
    systemctl disable multilarm-cpu-governor.service 2>/dev/null || true
    rm -f /etc/systemd/system/multilarm-cpu-governor.service
    systemctl daemon-reload 2>/dev/null || true
    # The governor itself stays at "performance" until next reboot — we
    # don't try to restore "ondemand" here because we don't know what
    # the host's pre-Multilarm default was. Reboot completes the revert.
    echo "Removed. Reboot to restore the distro default governor."
fi

# Always remove the sudoers drop-in (idempotent). Leaving it would let a
# subsequent reinstall accidentally pick up stale, possibly-wrong user
# scoping. Safe to rm even if the unit removal above was skipped.
if [[ -f /etc/sudoers.d/multilarm-governor ]]; then
    rm -f /etc/sudoers.d/multilarm-governor
    echo "Removed sudoers drop-in: /etc/sudoers.d/multilarm-governor"
fi

# ------------------------------------------------------------
# Remove helper scripts
# ------------------------------------------------------------

echo ""
echo "--- Removing helper scripts ---"

for script in "$REAL_HOME/.multilarm-wait-audio.sh" "$REAL_HOME/.multilarm-wait-clock.sh"; do
    if [[ -f "$script" ]]; then
        rm -f "$script"
        echo "Removed: $script"
    fi
done

# ------------------------------------------------------------
# Remove Multilarm binary and debug symbols
# ------------------------------------------------------------

echo ""
echo "--- Removing Multilarm binary ---"

if [[ -f "$REAL_HOME/Multilarm" ]]; then
    rm -f "$REAL_HOME/Multilarm"
    echo "Removed: $REAL_HOME/Multilarm"
fi

# ------------------------------------------------------------
# Remove Multilarm config file
# ------------------------------------------------------------

if [[ -f "$REAL_HOME/Multilarm.config.xml" ]]; then
    echo ""
    if ask_yes_no "Remove Multilarm configuration file ($REAL_HOME/Multilarm.config.xml)?"; then
        rm -f "$REAL_HOME/Multilarm.config.xml"
        echo "Removed: Multilarm.config.xml"
    else
        echo "Kept: Multilarm.config.xml"
    fi
fi

# ------------------------------------------------------------
# Remove Adhan sample library
# ------------------------------------------------------------

if [[ -d "$REAL_HOME/Adhan" ]]; then
    echo ""
    if ask_yes_no "Remove Adhan sample library ($REAL_HOME/Adhan)?"; then
        rm -rf "$REAL_HOME/Adhan"
        echo "Removed: Adhan directory"
    else
        echo "Kept: Adhan directory"
    fi
fi

# ------------------------------------------------------------
# Remove miniaudio wrapper native library from /usr/local/lib (optional)
# ------------------------------------------------------------

echo ""
if ask_yes_no "Remove the miniaudio wrapper library from /usr/local/lib?"; then
    AUDIO_LIB="/usr/local/lib/libmultilarm_audio.so"
    if [[ -f "$AUDIO_LIB" ]]; then
        rm -f "$AUDIO_LIB"
        echo "Removed: $AUDIO_LIB"
    else
        echo "No Multilarm audio library found in /usr/local/lib."
    fi

    # Remove ld.so config and refresh cache
    LIBCONF="/etc/ld.so.conf.d/multilarm_audio.conf"
    if [[ -f "$LIBCONF" ]]; then
        rm -f "$LIBCONF"
        echo "Removed: $LIBCONF"
    fi

    ldconfig
else
    echo "Kept: Multilarm audio library"
fi

# ------------------------------------------------------------
# Detect legacy artifacts that Multilarm CLEARLY installed
# ------------------------------------------------------------
#
# Multilarm's pre-self-contained installer (framework-dependent .NET, ARM32
# build on 64-bit hosts) wrote two signature lines into the user's .bashrc:
#
#   export DOTNET_ROOT=$HOME/.dotnet          -> it installed ~/.dotnet
#   export LD_LIBRARY_PATH=/usr/lib/aarch64-linux-gnu:...
#                                             -> it set up the armhf cross-arch
#                                                runtime on this aarch64 box
#
# The current self-contained installer writes NEITHER. So the presence of one
# of these lines is proof that Multilarm itself put the matching heavy artifact
# there — only then do we offer/perform its removal. We capture the markers
# HERE, before the .bashrc scrub below deletes the very lines we test for.

BASHRC="$REAL_HOME/.bashrc"
DOTNET_BY_MULTILARM=false
ARMHF_BY_MULTILARM=false

if [[ -f "$BASHRC" ]]; then
    grep -qE 'export DOTNET_ROOT=\$HOME/\.dotnet' "$BASHRC" 2>/dev/null \
        && DOTNET_BY_MULTILARM=true
    grep -qE 'export LD_LIBRARY_PATH=/usr/lib/aarch64-linux-gnu' "$BASHRC" 2>/dev/null \
        && ARMHF_BY_MULTILARM=true
fi

# ------------------------------------------------------------
# Clean up .bashrc entries
# ------------------------------------------------------------

echo ""
echo "--- Cleaning .bashrc environment variables ---"

if [[ -f "$BASHRC" ]]; then
    # Every line any Multilarm installer (current or legacy) may have added.
    # The legacy .NET / aarch64 entries are harmless no-ops on modern installs
    # (grep simply won't match) and get scrubbed on legacy ones.
    PATTERNS=(
        'export DOTNET_ROOT=\$HOME/\.dotnet'
        'export PATH=\$DOTNET_ROOT:\$PATH'
        'export DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1'
        'export LD_LIBRARY_PATH=/usr/local/lib:\$LD_LIBRARY_PATH'
        'export LD_LIBRARY_PATH=/usr/lib/aarch64-linux-gnu:\$LD_LIBRARY_PATH'
    )

    CLEANED=false
    for pattern in "${PATTERNS[@]}"; do
        if grep -qE "$pattern" "$BASHRC" 2>/dev/null; then
            # Use '|' as the sed address delimiter: the patterns contain '/'
            # (e.g. /usr/local/lib), which would otherwise terminate a default
            # /.../ address and make sed error out (aborting under set -e).
            sed -i "\|$pattern|d" "$BASHRC"
            CLEANED=true
        fi
    done

    if [[ "$CLEANED" == true ]]; then
        chown "$REAL_USER:$REAL_USER" "$BASHRC"
        echo "Removed Multilarm environment variables from .bashrc"
    else
        echo "No Multilarm entries found in .bashrc"
    fi
fi

# ------------------------------------------------------------
# Remove legacy .NET runtime — only if Multilarm installed it
# ------------------------------------------------------------
#
# ~/.dotnet is home-scoped and provably Multilarm's (DOTNET_ROOT marker), so we
# just remove it — no prompt, consistent with how the binary/service/helpers are
# removed unconditionally. Skipped entirely when the marker is absent, so a
# .dotnet some OTHER app installed is never touched.

if [[ "$DOTNET_BY_MULTILARM" == true && -d "$REAL_HOME/.dotnet" ]]; then
    echo ""
    echo "--- Removing legacy .NET runtime (installed by Multilarm) ---"
    rm -rf "$REAL_HOME/.dotnet"
    echo "Removed: $REAL_HOME/.dotnet"
fi

# ------------------------------------------------------------
# Remove legacy armhf compat packages — only if Multilarm set them up
# ------------------------------------------------------------
#
# These are SYSTEM-WIDE (dpkg architecture + shared libs), heavier and harder to
# undo than a home dir, and another app could conceivably rely on them. So even
# with the Multilarm fingerprint present we still confirm before removing
# (ask_yes_no keeps them in non-interactive curl|bash mode, removes under --yes).

ARCH=$(uname -m)
if [[ "$ARMHF_BY_MULTILARM" == true && "$ARCH" == "aarch64" ]]; then
    echo ""
    if ask_yes_no "Remove the armhf compat packages Multilarm installed? Skip if other apps now use them"; then
        apt-get remove -y \
            zlib1g:armhf \
            libstdc++6:armhf \
            libicu-dev:armhf \
            libasound2-plugins:armhf 2>/dev/null || true

        dpkg --remove-architecture armhf 2>/dev/null || true
        apt-get update 2>/dev/null || true
        echo "Removed armhf compatibility packages."
    else
        echo "Kept: armhf compatibility packages"
    fi
fi

# ------------------------------------------------------------
# Disable lingering (optional)
# ------------------------------------------------------------

echo ""
if ask_yes_no "Disable login lingering for $REAL_USER? Skip if other user services need it"; then
    loginctl disable-linger "$REAL_USER" 2>/dev/null || true
    echo "Disabled lingering for $REAL_USER"
else
    echo "Kept: lingering enabled"
fi

# ------------------------------------------------------------
# Done
# ------------------------------------------------------------

echo ""
echo "==================== Multilarm Uninstalled ===================="
echo ""
echo "You may want to reboot to ensure all changes take effect."
