#!/usr/bin/env bash

MODULE_USER_GROUPS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_USER_GROUPS_PROJECT_ROOT="$(cd "$MODULE_USER_GROUPS_DIR/../../.." && pwd)"

# shellcheck source=modules/system/user-groups/config.sh
source "$MODULE_USER_GROUPS_DIR/config.sh"
# shellcheck source=modules/system/user-groups/metadata.conf
source "$MODULE_USER_GROUPS_DIR/metadata.conf"

module_user_groups_metadata() {
  printf '%s|%s|%s\n' "$MODULE_ID" "$MODULE_NAME" "$MODULE_DESCRIPTION"
}

module_user_groups_normalize_csv() {
  local raw_groups="$1"

  printf '%s\n' "$raw_groups" \
    | tr ',' '\n' \
    | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' \
    | sed '/^$/d'
}

module_user_groups_check() {
  local target_user="${1:-$POSTINSTALL_USER_GROUPS_TARGET_USER}"
  local requested_groups="${2:-$POSTINSTALL_USER_GROUPS_DEFAULT_GROUPS}"
  local group_name=""

  if ! system_user_exists "$target_user"; then
    ui_error "Utilisateur introuvable : $target_user"
    return 1
  fi

  while IFS= read -r group_name; do
    if ! system_group_exists "$group_name"; then
      ui_warn "Groupe introuvable : $group_name"
      return 1
    fi

    if ! system_user_in_group "$target_user" "$group_name"; then
      ui_warn "Utilisateur $target_user non membre du groupe $group_name"
      return 1
    fi
  done < <(module_user_groups_normalize_csv "$requested_groups")

  ui_success "Tous les groupes demandes sont deja appliques a $target_user"
}

module_user_groups_install() {
  local target_user="${1:-$POSTINSTALL_USER_GROUPS_TARGET_USER}"
  local requested_groups="${2:-$POSTINSTALL_USER_GROUPS_DEFAULT_GROUPS}"
  local group_name=""
  local changed=0

  if ! system_user_exists "$target_user"; then
    ui_error "Impossible de configurer les groupes : utilisateur absent ($target_user)"
    return 1
  fi

  while IFS= read -r group_name; do
    if ! system_group_exists "$group_name"; then
      ui_warn "Groupe ignore car absent : $group_name"
      continue
    fi

    if system_user_in_group "$target_user" "$group_name"; then
      ui_info "Aucun changement : $target_user est deja dans $group_name"
      continue
    fi

    usermod -aG "$group_name" "$target_user"
    log_info "Utilisateur $target_user ajoute au groupe $group_name"
    ui_success "Utilisateur $target_user ajoute au groupe $group_name"
    changed=1
  done < <(module_user_groups_normalize_csv "$requested_groups")

  if [[ "$changed" -eq 0 ]]; then
    ui_info "Aucun changement de groupes necessaire"
  fi
}

module_user_groups_test() {
  local target_user="${1:-$POSTINSTALL_USER_GROUPS_TARGET_USER}"
  local requested_groups="${2:-$POSTINSTALL_USER_GROUPS_DEFAULT_GROUPS}"
  local group_name=""

  system_user_exists "$target_user" || return 1

  while IFS= read -r group_name; do
    system_group_exists "$group_name" || return 1
    system_user_in_group "$target_user" "$group_name" || return 1
  done < <(module_user_groups_normalize_csv "$requested_groups")
}
