#!/bin/bash
#
# gen-mdm-user-generator - systemd generator for per-user MDM services
#
# Creates service triggers for human users (UID >= 1000) to run
# user-specific Ansible playbooks on session start.
#
# Systemd generators run at boot time to dynamically create units.
#

set -euo pipefail

# Generator receives output directories as arguments
NORMAL_DIR="${1:-/run/systemd/generator}"
# EARLY_DIR="$2"   # For early boot (unused)
# LATE_DIR="$3"    # For late boot (unused)

# Exit if output directory doesn't exist
[[ ! -d "$NORMAL_DIR" ]] && exit 0

# Get human users (UID >= 1000, valid shell) from local /etc/passwd only.
# Must NOT use getent passwd — that triggers NSS/authd which queries the network
# (Azure AD via authd), causing each daemon-reload to block for 45+ seconds.
get_human_users() {
    awk -F: '$3 >= 1000 && $3 < 65534 && $7 !~ /nologin|false/ {print $1 ":" $3}' /etc/passwd
}

# Create wants directory for user session targets
mkdir -p "${NORMAL_DIR}/default.target.wants"

# Process each human user
while IFS=: read -r username uid; do
    [[ -z "$username" ]] && continue

    # Create a drop-in to trigger MDM user service when user session starts
    # This links gen-mdm-user@{username}.service to run after user login
    user_target_dir="${NORMAL_DIR}/user@${uid}.service.wants"
    mkdir -p "$user_target_dir"

    # Create symlink to trigger user playbooks
    ln -sf "/lib/systemd/system/gen-mdm-user@.service" \
        "${user_target_dir}/gen-mdm-user@${username}.service"

done < <(get_human_users)

exit 0