#!/usr/bin/env bash

# To use this script, you'll want to put this in your systemd service:
# rm /etc/gshadow
# systemd-sysusers
# (run this script)
# systemd-tmpfiles --create --remove --boot --exclude-prefix=/dev
# This will populate /etc/group successfully, and then populate /etc/gshadow
# with any missing groups that we nuked when we removed /etc/gshadow
#
# TODO: This entire script is a workaround for systemd-sysusers not managing
# /etc/gshadow on bootc images. Remove once upstream resolves it:
# https://github.com/systemd/systemd/issues/30852
#
# GSHADOW_FILE / GROUP_FILE env-var overrides exist solely for unit-test
# isolation (bats cannot write to /etc). Remove them when this script is
# deleted.
GSHADOW_FILE="${GSHADOW_FILE:-/etc/gshadow}"
GROUP_FILE="${GROUP_FILE:-/etc/group}"

(
    flock -x 9
    while IFS=: read -r group_name _rest; do
        grep -q "^${group_name}:" "$GSHADOW_FILE" 2>/dev/null || \
            printf '%s:!*::\n' "$group_name" >> "$GSHADOW_FILE"
    done < "$GROUP_FILE"
) 9>>"${GSHADOW_FILE}"
