#!/usr/bin/env bash
if [[ -z "${BASH_VERSION:-}" ]]; then
  echo "ERROR: This uninstaller must be run with bash, as root." >&2
  echo "Example: curl -fsSL https://shop.softmaker.com/uninstall-softmaker-freeoffice-2024.sh | bash -s -- [args]" >&2
  exit 2
fi

set -euo pipefail

# SoftMaker Office 2024 unified uninstaller

PACKAGE_DEFAULT="softmaker-freeoffice-2024"

# APT repo artifacts (match installer)
APT_KEYRING_PATH="/etc/apt/keyrings/softmaker.gpg"
APT_LIST_PATH="/etc/apt/sources.list.d/softmaker.list"

# DNF repo artifact (match installer)
DNF_REPO_PATH="/etc/yum.repos.d/softmaker.repo"

# Zypper repo alias (match installer)
ZYPPER_REPO_ALIAS_DEFAULT="SoftMaker"

log()  { printf '%s\n' "==> $*"; }
warn() { printf '%s\n' "WARNING: $*" >&2; }
die()  { printf '%s\n' "ERROR: $*" >&2; exit 1; }

usage() {
  cat <<'EOF'
SoftMaker Office 2024 uninstaller

Usage:
  uninstall-softmaker-freeoffice-2024.sh [options]

Options:
  --package NAME           Package to remove (default: softmaker-freeoffice-2024)
  --keep-repo              Do not remove SoftMaker repo config (default: remove it)
  --purge                  For APT: use purge (remove package + config). Default is remove.
  --autoremove             For APT: run autoremove after uninstall
  --dry-run                Print what would be done, don't change anything
  --force-apt|--force-dnf|--force-zypper|--force-pamac|--force-tgz
  --zypper-alias NAME      Zypper repo alias to remove (default: SoftMaker)
  -h|--help                Show help

Examples:
  # Using sudo:
  curl -fsSL https://shop.softmaker.com/uninstall-softmaker-freeoffice-2024.sh | sudo bash
  # Using su:
  su -c 'curl -fsSL https://shop.softmaker.com/uninstall-softmaker-freeoffice-2024.sh | bash'
  # As root:
  bash uninstall-softmaker-freeoffice-2024.sh --purge --autoremove
EOF
}

PACKAGE="$PACKAGE_DEFAULT"
KEEP_REPO=0
PURGE=0
AUTOREMOVE=0
DRY_RUN=0
FORCE_PM=""
ZYPPER_REPO_ALIAS="$ZYPPER_REPO_ALIAS_DEFAULT"

run() {
  if [[ "$DRY_RUN" -eq 1 ]]; then
    printf '[dry-run] %q ' "$@"; printf '\n'
  else
    "$@"
  fi
}

as_root_or_die() {
  if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
    die "This script must be run as root (e.g. via sudo, su, or login as root)."
  fi
}

parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --package)
        [[ -n "${2:-}" ]] || die "--package requires a value"
        PACKAGE="$2"; shift 2 ;;
      --keep-repo) KEEP_REPO=1; shift ;;
      --purge) PURGE=1; shift ;;
      --autoremove) AUTOREMOVE=1; shift ;;
      --dry-run) DRY_RUN=1; shift ;;
      --force-apt) FORCE_PM="apt"; shift ;;
      --force-dnf) FORCE_PM="dnf"; shift ;;
      --force-zypper) FORCE_PM="zypper"; shift ;;
      --force-pamac) FORCE_PM="pamac"; shift ;;
      --force-tgz) FORCE_PM="tgz"; shift ;;
      --zypper-alias)
        [[ -n "${2:-}" ]] || die "--zypper-alias requires a value"
        ZYPPER_REPO_ALIAS="$2"; shift 2 ;;
      -h|--help) usage; exit 0 ;;
      *) die "Unknown option: $1 (use --help)" ;;
    esac
  done
}

detect_pm() {
  if [[ -n "$FORCE_PM" ]]; then
    echo "$FORCE_PM"
    return 0
  fi

  # Check apt before pamac - more predictable on systems with both
  if command -v apt-get >/dev/null 2>&1; then
    echo "apt"; return 0
  elif command -v dnf >/dev/null 2>&1; then
    echo "dnf"; return 0
  elif command -v zypper >/dev/null 2>&1; then
    echo "zypper"; return 0
  elif command -v pamac >/dev/null 2>&1; then
    echo "pamac"; return 0
  else
    echo "tgz"; return 0
  fi
}

uninstall_apt() {
  log "Detected APT (Debian/Ubuntu/Mint). Removing package '$PACKAGE'..."

  run apt-get update

  if [[ "$PURGE" -eq 1 ]]; then
    run apt-get -y purge "$PACKAGE" || warn "Package purge failed or package not installed."
  else
    run apt-get -y remove "$PACKAGE" || warn "Package remove failed or package not installed."
  fi

  if [[ "$AUTOREMOVE" -eq 1 ]]; then
    run apt-get -y autoremove || warn "autoremove failed."
  fi

  if [[ "$KEEP_REPO" -eq 0 ]]; then
    log "Removing SoftMaker APT repo configuration..."
    if [[ -f "$APT_LIST_PATH" ]]; then
      run rm -f "$APT_LIST_PATH"
    else
      log "APT sources file not found: $APT_LIST_PATH (already removed?)"
    fi

    # Only remove the keyring if it looks like it's SoftMaker's.
    # (If you share the keyring for multiple SoftMaker products, use --keep-repo.)
    if [[ -f "$APT_KEYRING_PATH" ]]; then
      run rm -f "$APT_KEYRING_PATH"
    else
      log "APT keyring not found: $APT_KEYRING_PATH (already removed?)"
    fi

    run apt-get update
  else
    log "Keeping SoftMaker APT repo configuration (--keep-repo)."
  fi

  log "Done."
}

uninstall_dnf() {
  log "Detected DNF (Fedora/RHEL-family). Removing package '$PACKAGE'..."
  run dnf -y remove "$PACKAGE" || warn "Package remove failed or package not installed."

  if [[ "$KEEP_REPO" -eq 0 ]]; then
    log "Removing SoftMaker DNF repo file..."
    if [[ -f "$DNF_REPO_PATH" ]]; then
      run rm -f "$DNF_REPO_PATH"
    else
      log "DNF repo file not found: $DNF_REPO_PATH (already removed?)"
    fi
    run dnf -y clean all || warn "dnf clean all failed."
    run dnf -y makecache || warn "dnf makecache failed."
  else
    log "Keeping SoftMaker DNF repo configuration (--keep-repo)."
  fi

  log "Done."
}

uninstall_zypper() {
  log "Detected Zypper (openSUSE). Removing package '$PACKAGE'..."
  run zypper -n remove "$PACKAGE" || warn "Package remove failed or package not installed."

  if [[ "$KEEP_REPO" -eq 0 ]]; then
    log "Removing Zypper repo alias '$ZYPPER_REPO_ALIAS'..."
    # If alias doesn't exist, rr returns non-zero—treat as non-fatal.
    run zypper -n rr "$ZYPPER_REPO_ALIAS" || warn "Repo alias '$ZYPPER_REPO_ALIAS' not found (already removed?)"
    run zypper -n ref || warn "zypper refresh failed."
  else
    log "Keeping SoftMaker Zypper repo configuration (--keep-repo)."
  fi

  log "Done."
}

uninstall_pamac() {
  log "Detected Pamac (Manjaro). Removing package '$PACKAGE'..."
  # pamac remove supports --no-confirm on many systems; if it fails, fall back interactively.
  if [[ "$DRY_RUN" -eq 1 ]]; then
    run pamac remove --no-confirm "$PACKAGE"
  else
    if ! pamac remove --no-confirm "$PACKAGE"; then
      warn "Non-interactive pamac remove failed (maybe --no-confirm unsupported). Retrying interactively..."
      pamac remove "$PACKAGE"
    fi
  fi

  if [[ "$KEEP_REPO" -eq 0 ]]; then
    log "No external repo config to remove for pamac/pacman path."
  fi

  log "Done."
}

uninstall_tgz() {
  log "No supported package manager detected (or forced TGZ)."

  local tgz_uninstaller="/usr/bin/uninstall_smoffice2024"

  if [[ -x "$tgz_uninstaller" ]]; then
    log "Found TGZ uninstaller: $tgz_uninstaller"
    log "Running TGZ uninstaller…"

    if [[ "$DRY_RUN" -eq 1 ]]; then
      printf '[dry-run] %q\n' "$tgz_uninstaller"
      return 0
    fi

    # IMPORTANT: when script is piped into bash, stdin is not a TTY.
    # Redirect stdin from /dev/tty so the user can answer prompts.
    if [[ -t 0 ]] || [[ ! -r /dev/tty ]]; then
      "$tgz_uninstaller"
    else
      "$tgz_uninstaller" </dev/tty
    fi

    log "Done. SoftMaker Office 2024 removed via TGZ uninstaller."
    return 0
  fi

  cat <<'EOF'
TGZ installs are uninstallable via:
  /usr/bin/uninstall_smoffice2024

However, that file was not found or is not executable on this system.

Best-effort suggestions:
1) Verify the uninstaller exists:
   ls -l /usr/bin/uninstall_smoffice2024
2) If it exists but is not executable:
   chmod +x /usr/bin/uninstall_smoffice2024
EOF
}

main() {
  parse_args "$@"
  as_root_or_die

  local pm
  pm="$(detect_pm)"
  log "Uninstaller mode: ${pm} (package: $PACKAGE)"

  case "$pm" in
    apt) uninstall_apt ;;
    dnf) uninstall_dnf ;;
    zypper) uninstall_zypper ;;
    pamac) uninstall_pamac ;;
    tgz) uninstall_tgz ;;
    *) die "Internal error: unknown pm '$pm'" ;;
  esac
}

main "$@"
