#!/usr/bin/env bash
# policy: dev_no-local-users — lock local account passwords so only FreeIPA accounts can auth.
# Applied when host is member of dev_no-local-users host-group.
# Revert: unlocks every account that was locked by this policy.

NO_LOCAL_USERS_STATE="$STATE_DIR/no-local-users"

_apply_no_local_users() {
    log "Applying no_local_users policy — locking local account passwords"
    [[ -f "$NO_LOCAL_USERS_STATE" ]] || touch "$NO_LOCAL_USERS_STATE"

    while IFS=: read -r uname _ uid _; do
        [[ "$uid" =~ ^[0-9]+$ ]] || continue
        { [[ "$uid" == "0" ]] || [[ "$uid" -ge 1000 ]]; } || continue

        grep -qxF "$uname" "$NO_LOCAL_USERS_STATE" 2>/dev/null && continue

        local hash
        hash=$(getent shadow "$uname" 2>/dev/null | cut -d: -f2 || true)
        [[ -z "$hash" || "$hash" == '!'* || "$hash" == '*'* ]] && continue

        if passwd -l "$uname" &>/dev/null; then
            echo "$uname" >> "$NO_LOCAL_USERS_STATE"
            log "Locked local account: $uname"
        else
            warn "Failed to lock local account: $uname"
        fi
    done < /etc/passwd
}

_revert_no_local_users() {
    [[ -f "$NO_LOCAL_USERS_STATE" ]] || return 0
    log "Reverting no_local_users policy — unlocking previously locked accounts"
    while IFS= read -r uname; do
        [[ -z "$uname" ]] && continue
        if passwd -u "$uname" &>/dev/null; then
            log "Unlocked local account: $uname"
        else
            warn "Failed to unlock local account: $uname (may have been removed)"
        fi
    done < "$NO_LOCAL_USERS_STATE"
    > "$NO_LOCAL_USERS_STATE"
}

if [[ "$WANT_NO_LOCAL_USERS" == true ]]; then
    _apply_no_local_users
else
    if [[ -f "$NO_LOCAL_USERS_STATE" ]] && [[ -s "$NO_LOCAL_USERS_STATE" ]]; then
        _revert_no_local_users
    fi
fi
