#!/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_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
        }
      }
    }'
}
