#!/usr/bin/env bash

system_require_bash() {
  if [[ -z "${BASH_VERSION:-}" ]]; then
    printf 'Bash est requis.\n' >&2
    exit 1
  fi
}

system_require_debian() {
  if [[ ! -r /etc/os-release ]]; then
    ui_error "Impossible de detecter le systeme"
    exit 1
  fi

  if ! grep -Eq '^ID=debian$|^ID_LIKE=.*debian' /etc/os-release; then
    ui_error "Ce script cible Debian"
    exit 1
  fi

  ui_success "Systeme Debian detecte"
}

system_require_root() {
  if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
    ui_error "Relancer ce script avec sudo ou en root"
    exit 1
  fi

  ui_success "Privileges root valides"
}

system_can_prompt_password() {
  [[ -t 0 && -t 1 ]]
}

system_reexec_as_root() {
  local entrypoint="${POSTINSTALL_ENTRYPOINT:-}"
  local quoted_args=""
  local arg=""

  if [[ "${EUID:-$(id -u)}" -eq 0 ]]; then
    return 0
  fi

  if [[ -z "$entrypoint" || ! -f "$entrypoint" ]]; then
    ui_error "Impossible de relancer automatiquement en root depuis cette execution"
    return 1
  fi

  if ! system_can_prompt_password; then
    ui_error "Privileges root requis et aucun terminal interactif disponible"
    return 1
  fi

  for arg in "$@"; do
    quoted_args="${quoted_args} $(printf '%q' "$arg")"
  done

  if command -v sudo >/dev/null 2>&1; then
    ui_info "Privileges root requis, tentative avec sudo"
    exec sudo --preserve-env=TMPDIR bash "$entrypoint" "$@"
  fi

  if command -v su >/dev/null 2>&1; then
    ui_info "Privileges root requis, bascule vers root avec su"
    exec su -c "bash $(printf '%q' "$entrypoint")$quoted_args"
  fi

  ui_error "Ni sudo ni su ne sont disponibles pour obtenir les privileges root"
  return 1
}

system_user_exists() {
  local user_name="$1"
  id "$user_name" >/dev/null 2>&1
}

system_group_exists() {
  local group_name="$1"
  getent group "$group_name" >/dev/null 2>&1
}

system_user_in_group() {
  local user_name="$1"
  local group_name="$2"
  id -nG "$user_name" 2>/dev/null | tr ' ' '\n' | grep -Fx "$group_name" >/dev/null 2>&1
}

system_primary_interface() {
  ip route get 1.1.1.1 2>/dev/null | awk '
    /dev/ {
      for (i = 1; i <= NF; i++) {
        if ($i == "dev") {
          print $(i + 1)
          exit
        }
      }
    }'
}

system_origin_user() {
  if [[ -n "${SUDO_USER:-}" ]]; then
    printf '%s\n' "$SUDO_USER"
    return 0
  fi

  if [[ -n "${PKEXEC_UID:-}" ]]; then
    getent passwd "$PKEXEC_UID" | cut -d: -f1
    return 0
  fi

  printf '%s\n' "$(id -un)"
}

system_privilege_mode() {
  if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
    printf 'utilisateur\n'
  elif [[ -n "${SUDO_USER:-}" ]]; then
    printf 'sudo\n'
  else
    printf 'root direct\n'
  fi
}
