#!/usr/bin/env bash
# policy: dev_local-sudo — per-device sudo grant for named local users.
# dev_local-sudo-<username>: adds a sudoers drop-in; removed when host leaves group.

LOCAL_SUDO_DIR="/etc/sudoers.d"
LOCAL_SUDO_STATE="$STATE_DIR/local-sudo-users"
[[ -f "$LOCAL_SUDO_STATE" ]] || touch "$LOCAL_SUDO_STATE"

for _USER in "${ACTIVE_LOCAL_SUDO_USERS[@]+"${ACTIVE_LOCAL_SUDO_USERS[@]}"}"; do
    _DROPIN="$LOCAL_SUDO_DIR/ansipa-local-sudo-${_USER}"
    if [[ ! -f "$_DROPIN" ]]; then
        log "Granting local sudo to $_USER on this device"
        echo "$_USER ALL=(ALL) ALL" > "$_DROPIN"
        chmod 440 "$_DROPIN"
    fi
    grep -qxF "$_USER" "$LOCAL_SUDO_STATE" 2>/dev/null || echo "$_USER" >> "$LOCAL_SUDO_STATE"
done

# Revoke sudo for users no longer in any active dev_local-sudo-* group.
while IFS= read -r _OLD_USER; do
    [[ -z "$_OLD_USER" ]] && continue
    _still_active=false
    for _U in "${ACTIVE_LOCAL_SUDO_USERS[@]+"${ACTIVE_LOCAL_SUDO_USERS[@]}"}"; do
        [[ "$_U" == "$_OLD_USER" ]] && _still_active=true && break
    done
    if [[ "$_still_active" == false ]]; then
        _DROPIN="$LOCAL_SUDO_DIR/ansipa-local-sudo-${_OLD_USER}"
        if [[ -f "$_DROPIN" ]]; then
            rm -f "$_DROPIN"
            log "Revoked local sudo for $_OLD_USER (host left dev_local-sudo-$_OLD_USER group)"
        fi
    fi
done < "$LOCAL_SUDO_STATE"

if [[ ${#ACTIVE_LOCAL_SUDO_USERS[@]} -gt 0 ]]; then
    printf '%s\n' "${ACTIVE_LOCAL_SUDO_USERS[@]}" | sort -u > "$LOCAL_SUDO_STATE"
else
    > "$LOCAL_SUDO_STATE"
fi
unset _USER _DROPIN _OLD_USER _still_active _U
