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

set -euo pipefail

# SoftMaker Office 2024 unified installer

PACKAGE_DEFAULT="softmaker-office-2024"
APT_REPO_URL_DEFAULT="https://shop.softmaker.com/repo/apt"
APT_KEY_URL_DEFAULT="https://shop.softmaker.com/repo/apt/softmaker-repo.asc"
DNF_REPOFILE_URL_DEFAULT="https://shop.softmaker.com/repo/softmaker.repo"
ZYPPER_REPO_URL_DEFAULT="https://shop.softmaker.com/repo/rpm"
ZYPPER_REPO_NAME_DEFAULT="SoftMaker"
CHANNEL_DEFAULT="stable"

# Stable "latest" tgz URL
TGZ_URL_DEFAULT="https://softmaker.net/down/softmaker-office-2024-latest.tgz"

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

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

Usage:
  install-softmaker-office-2024.sh [options]

Options:
  --package NAME         Package name to install (default: softmaker-office-2024)
  --channel NAME         Repo channel for APT (default: stable)
  --assume-yes           Non-interactive install where possible (default)
  --no-assume-yes        Ask confirmations (more interactive)
  --dry-run              Print what would be done, don't change anything
  --force-apt|--force-dnf|--force-zypper|--force-pamac|--force-tgz
  --tgz-url URL          TGZ fallback URL (for unsupported distros)
  -h|--help              Show this help

Examples:
  # Using sudo:
  curl -fsSL https://shop.softmaker.com/install-softmaker-office-2024.sh | sudo bash
  # Using su:
  su -c 'curl -fsSL https://shop.softmaker.com/install-softmaker-office-2024.sh | bash'
  # As root:
  bash install-softmaker-office-2024.sh --channel stable
EOF
}

# Defaults (can be overridden by args)
PACKAGE="$PACKAGE_DEFAULT"
CHANNEL="$CHANNEL_DEFAULT"
APT_REPO_URL="$APT_REPO_URL_DEFAULT"
APT_KEY_URL="$APT_KEY_URL_DEFAULT"
DNF_REPOFILE_URL="$DNF_REPOFILE_URL_DEFAULT"
ZYPPER_REPO_URL="$ZYPPER_REPO_URL_DEFAULT"
ZYPPER_REPO_NAME="$ZYPPER_REPO_NAME_DEFAULT"
TGZ_URL="$TGZ_URL_DEFAULT"

ASSUME_YES=1
DRY_RUN=0
FORCE_PM=""   # apt|dnf|zypper|pamac|tgz

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

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || die "Required command not found: $1"
}

# Download helper - uses curl or wget, whichever is available
download() {
  local url="$1" dest="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL --retry 3 --retry-delay 1 -o "$dest" "$url"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$dest" "$url"
  else
    die "Neither curl nor wget found. Please install one."
  fi
}

# Download to stdout
download_stdout() {
  local url="$1"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$url"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO- "$url"
  else
    die "Neither curl nor wget found. Please install one."
  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
}

check_arch() {
  local arch
  arch="$(uname -m || true)"
  case "$arch" in
    x86_64|amd64) ;;
    *)
      die "Unsupported architecture '$arch'. SoftMaker Office 2024 is 64-bit x86_64/amd64 only."
      ;;
  esac
}

parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --package)
        [[ -n "${2:-}" ]] || die "--package requires a value"
        PACKAGE="$2"; shift 2 ;;
      --channel)
        [[ -n "${2:-}" ]] || die "--channel requires a value"
        CHANNEL="$2"; shift 2 ;;
      --assume-yes) ASSUME_YES=1; shift ;;
      --no-assume-yes) ASSUME_YES=0; 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 ;;
      --tgz-url)
        [[ -n "${2:-}" ]] || die "--tgz-url requires a value"
        TGZ_URL="$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
}

install_apt() {
  log "Detected APT (Debian/Ubuntu/Mint). Installing via SoftMaker APT repository..."
  export DEBIAN_FRONTEND=noninteractive

  run mkdir -p /etc/apt/keyrings

  # Ensure basic tooling exists (gpg/ca-certificates).
  local apt_yes=()
  if [[ "$ASSUME_YES" -eq 1 ]]; then apt_yes=(-y); fi

  run apt-get update
  run apt-get install ${apt_yes[@]+"${apt_yes[@]}"} gnupg ca-certificates

  # Import key into keyring (idempotent).
  local keyring="/etc/apt/keyrings/softmaker.gpg"
  local keytmp
  keytmp="$(mktemp)"
  if [[ "$DRY_RUN" -eq 1 ]]; then
    run bash -c "download_stdout '$APT_KEY_URL' | gpg --dearmor > '$keyring'"
  else
    download_stdout "$APT_KEY_URL" | gpg --dearmor > "$keytmp"
    install -m 0644 "$keytmp" "$keyring"
    rm -f "$keytmp"
  fi

  # Repo list
  local listfile="/etc/apt/sources.list.d/softmaker.list"
  local line="deb [signed-by=$keyring] $APT_REPO_URL $CHANNEL non-free"
  if [[ "$DRY_RUN" -eq 1 ]]; then
    run bash -c "echo \"$line\" > '$listfile'"
  else
    printf '%s\n' "$line" > "$listfile"
  fi

  run apt-get update
  run apt-get install ${apt_yes[@]+"${apt_yes[@]}"} "$PACKAGE"

  log "Done. SoftMaker Office 2024 installed via APT."
}

install_dnf() {
  log "Detected DNF (Fedora/RHEL-family). Installing via SoftMaker DNF repository..."

  local dnf_yes=()
  if [[ "$ASSUME_YES" -eq 1 ]]; then dnf_yes=(-y); fi

  if [[ "$DRY_RUN" -eq 1 ]]; then
    run download "$DNF_REPOFILE_URL" /etc/yum.repos.d/softmaker.repo
  else
    download "$DNF_REPOFILE_URL" /etc/yum.repos.d/softmaker.repo
  fi
  # Using makecache is typically faster/less disruptive than full upgrade.
  run dnf makecache ${dnf_yes[@]+"${dnf_yes[@]}"}
  run dnf install ${dnf_yes[@]+"${dnf_yes[@]}"} "$PACKAGE"

  log "Done. SoftMaker Office 2024 installed via DNF."
  log "If prompted to import the SoftMaker GPG key, please confirm."
}

install_zypper() {
  log "Detected Zypper (openSUSE). Installing via SoftMaker Zypper repository..."
  local zopts=()
  if [[ "$ASSUME_YES" -eq 1 ]]; then zopts=(-n); fi

  # 1) Ensure the repo signing key is in the RPM keyring (fixes "repomd.xml signed with unknown key")
  run rpm --import "https://shop.softmaker.com/repo/rpm/softmaker-repo.asc"

  # 2) Add repo if missing; otherwise keep it.
  if [[ -f /etc/zypp/repos.d/${ZYPPER_REPO_NAME}.repo ]]; then
    log "Repo '$ZYPPER_REPO_NAME' already exists; keeping it."
  else
    run zypper ${zopts[@]+"${zopts[@]}"} addrepo -f "$ZYPPER_REPO_URL" "$ZYPPER_REPO_NAME"
  fi

  # 3) Refresh + install
  run zypper ${zopts[@]+"${zopts[@]}"} --gpg-auto-import-keys ref
  run zypper ${zopts[@]+"${zopts[@]}"} install "$PACKAGE"

  log "Done. SoftMaker Office 2024 installed via Zypper."
}

install_pamac() {
  log "Detected Pamac (Manjaro). Installing via pamac..."
  local popts=()
  # pamac supports --no-confirm on many systems; if it fails, user can rerun without assume-yes.
  if [[ "$ASSUME_YES" -eq 1 ]]; then popts=(--no-confirm); fi

  if [[ "$DRY_RUN" -eq 1 ]]; then
    run pamac install ${popts[@]+"${popts[@]}"} "$PACKAGE"
  else
    if ! pamac install ${popts[@]+"${popts[@]}"} "$PACKAGE"; then
      warn "pamac non-interactive install failed (maybe --no-confirm unsupported). Retrying interactively..."
      pamac install "$PACKAGE"
    fi
  fi

  log "Done. SoftMaker Office 2024 installed via pamac."
}

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

  if [[ -z "${TGZ_URL:-}" ]]; then
    die "TGZ fallback needs a URL. Re-run with: --tgz-url https://softmaker.net/down/softmaker-office-2024-latest.tgz"
  fi

  need_cmd tar

  # Run the TGZ install in a subshell so the EXIT trap is scoped to this block only.
  (
    set -euo pipefail

    workdir="$(mktemp -d)"
    trap 'rm -rf "$workdir"' EXIT

    tgz="$workdir/softmaker-office-2024-latest.tgz"

    log "Downloading TGZ..."
    if [[ "$DRY_RUN" -eq 1 ]]; then
      run download "$TGZ_URL" "$tgz"
    else
      download "$TGZ_URL" "$tgz"
    fi

    log "Unpacking..."
    run tar -xvzf "$tgz" -C "$workdir"

    # Use head -n1 instead of -quit for POSIX compatibility
    installer="$(find "$workdir" -maxdepth 3 -type f -name installsmoffice 2>/dev/null | head -n1 || true)"
    [[ -n "$installer" ]] || die "Could not find 'installsmoffice' inside the TGZ."

    log "Running installer: $installer"
    run chmod +x "$installer"
    run "$installer"

    log "Done. SoftMaker Office 2024 installed via TGZ."
  )
}

main() {
  parse_args "$@"
  as_root_or_die
  check_arch

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

  case "$pm" in
    apt) install_apt ;;
    dnf) install_dnf ;;
    zypper) install_zypper ;;
    pamac) install_pamac ;;
    tgz) install_tgz ;;
    *) die "Internal error: unknown pm '$pm'" ;;
  esac
}

main "$@"
