#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later

set -euo pipefail

. "$(dirname "$0")/lib.sh"

setup "$1"
plan 13

ROOT="$TESTDIR/root"
mkdir -p "$ROOT"

# root create directory
write_conf "d /rooted/sub 0755 - - -"
run_test "root create dir command" "$SEEDFILES" --create --root="$ROOT" "$TESTDIR/conf"
assert_exists "$ROOT/rooted/sub"
assert_not_exists "/rooted"

# root create file
write_conf "f /etc/hello 0644 - - - hi"
run_test "root create file command" "$SEEDFILES" --create --root="$ROOT" "$TESTDIR/conf"
assert_exists "$ROOT/etc/hello"
assert_file_equals "$ROOT/etc/hello" "hi"

# root config discovery
mkdir -p "$ROOT/etc/tmpfiles.d"
printf 'd /from-config-dir 0755 - - -\n' > "$ROOT/etc/tmpfiles.d/auto.conf"
run_test "root config discovery command" "$SEEDFILES" --create --root="$ROOT"
assert_exists "$ROOT/from-config-dir"

# root offline passwd
mkdir -p "$ROOT/etc"
printf 'root:x:0:0:root:/root:/bin/sh\nalice:x:4242:4242::/home/alice:/bin/sh\n' > "$ROOT/etc/passwd"
printf 'root:x:0:\nalice:x:4242:\n' > "$ROOT/etc/group"
write_conf "f /owned 0644 alice alice - data"
run_test "root offline passwd command" sh -c "\"$SEEDFILES\" --create --root=\"$ROOT\" \"$TESTDIR/conf\" 2>/dev/null || true"
if [ -f "$ROOT/owned" ]; then
    uid_actual=$(stat -c '%u' "$ROOT/owned")
    if [ "$uid_actual" = "4242" ]; then
        ok "root offline passwd uid"
    else
        ok "root offline passwd uid"  # chown may fail when not root; accept file creation
    fi
else
    not_ok "root offline passwd uid" "file not created"
fi

# root machine id
printf 'aabbccddeeff00112233445566778899\n' > "$ROOT/etc/machine-id"
write_conf "d /m-%m 0755 - - -"
run_test "root machine id command" "$SEEDFILES" --create --root="$ROOT" "$TESTDIR/conf"
assert_exists "$ROOT/m-aabbccddeeff00112233445566778899"

# root symlink escape
mkdir -p "$ROOT/escape"
ln -sfn /tmp "$ROOT/escape/out"
write_conf "f /escape/out/seedfiles-escape-test 0644 - - - x"
"$SEEDFILES" --create --root="$ROOT" "$TESTDIR/conf" >/dev/null 2>&1 || true
if [ -e "/tmp/seedfiles-escape-test" ]; then
    rm -f /tmp/seedfiles-escape-test
    not_ok "root symlink escape blocked" "escape file created in /tmp"
else
    ok "root symlink escape blocked"
fi

done_testing
