#!/usr/bin/env bash
#
# uninstall.sh — remove the mbproxy service from a Linux / systemd host.
#
# The Linux counterpart of uninstall.ps1. Stops and disables the service,
# removes the systemd unit and installed files, and (unless --keep-config)
# removes the config directory. Log files are always preserved: they are moved
# to a timestamped archive so post-uninstall diagnostics remain accessible.
#
# Usage:
#   sudo ./uninstall.sh [--keep-config] [--keep-user]
#
#   --keep-config   leave /etc/mbproxy/appsettings.json in place.
#   --keep-user     leave the mbproxy service account in place.
#
set -euo pipefail

SERVICE_NAME="mbproxy"
SERVICE_USER="mbproxy"
INSTALL_DIR="/opt/mbproxy"
CONFIG_DIR="/etc/mbproxy"
LOG_DIR="/var/log/mbproxy"
CACHE_DIR="/var/cache/mbproxy"
UNIT_DEST="/etc/systemd/system/${SERVICE_NAME}.service"

keep_config=0
keep_user=0
while [[ $# -gt 0 ]]; do
    case "$1" in
        --keep-config) keep_config=1; shift ;;
        --keep-user)   keep_user=1; shift ;;
        *)             echo "Unknown argument: $1" >&2; exit 2 ;;
    esac
done

if [[ "$(id -u)" -ne 0 ]]; then
    echo "uninstall.sh must run as root (use sudo)." >&2
    exit 1
fi

echo "Uninstalling ${SERVICE_NAME} service..."

# ── 1. Stop + disable the service ────────────────────────────────────────────
if systemctl list-unit-files "${SERVICE_NAME}.service" >/dev/null 2>&1 \
   && [[ -n "$(systemctl list-unit-files "${SERVICE_NAME}.service" --no-legend 2>/dev/null)" ]]; then
    echo "Stopping and disabling '${SERVICE_NAME}'..."
    systemctl disable --now "$SERVICE_NAME" >/dev/null 2>&1 || true
fi

# ── 2. Remove the systemd unit ───────────────────────────────────────────────
if [[ -f "$UNIT_DEST" ]]; then
    echo "Removing systemd unit '${UNIT_DEST}'..."
    rm -f "$UNIT_DEST"
fi
systemctl daemon-reload
systemctl reset-failed "$SERVICE_NAME" >/dev/null 2>&1 || true

# ── 3. Archive logs (always preserved, never deleted) ────────────────────────
if [[ -d "$LOG_DIR" ]]; then
    timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
    archive_dir="${LOG_DIR}.archived-${timestamp}"
    echo "Archiving logs to '${archive_dir}'..."
    mv "$LOG_DIR" "$archive_dir"
fi

# ── 4. Remove installed files ────────────────────────────────────────────────
rm -rf "$INSTALL_DIR" "$CACHE_DIR"

if [[ "$keep_config" -eq 1 ]]; then
    echo "Keeping config at '${CONFIG_DIR}/appsettings.json' (--keep-config)."
else
    rm -rf "$CONFIG_DIR"
fi

# ── 5. Remove the service account ────────────────────────────────────────────
if [[ "$keep_user" -eq 0 ]] && id -u "$SERVICE_USER" >/dev/null 2>&1; then
    echo "Removing service account '${SERVICE_USER}'..."
    userdel "$SERVICE_USER" 2>/dev/null || true
fi

echo ""
echo "Uninstall complete."
if compgen -G "${LOG_DIR}.archived-*" >/dev/null; then
    echo "Archived logs: ${LOG_DIR}.archived-*"
fi
