#!/bin/sh
set -eu
work=$(mktemp -d)
trap 'rm -rf "$work"' 0
mkdir -p "$work/bin"
cp initify.pl "$work/bin/initify"
chmod 755 "$work/bin/initify"
export PATH="$work/bin:$PATH"
helper=$1
cat > "$work/example.service" <<'UNIT'
[Unit]
Description=Example foreground service
[Service]
Type=simple
ExecStart=/bin/sleep 300
[Install]
WantedBy=multi-user.target
UNIT
sh "$helper" systemd "$work/systemd" "$work/example.service"
cmp "$work/example.service" "$work/systemd/usr/lib/systemd/system/example.service"
[ ! -d "$work/systemd/etc/init.d" ]
sh "$helper" openrc "$work/openrc" "$work/example.service"
script=$work/openrc/etc/init.d/example
[ -x "$script" ]
grep -Fx 'command=/bin/sleep' "$script"
grep -Fx 'command_background=true' "$script"
grep -Fx 'pidfile=/run/example.pid' "$script"
[ ! -d "$work/openrc/usr/lib/systemd" ]
sh -n "$script"
for directive in 'User=nobody' 'EnvironmentFile=/etc/example' 'WorkingDirectory=/tmp' 'ExecStartPre=/bin/true' 'Type=oneshot' 'ProtectSystem=strict' 'ExecStart=/bin/sleep ${UNSAFE}' 'ExecStart=/bin/sleep %i' 'ExecStart=/bin/sleep 600'; do
    # Duplicate Type/ExecStart are also rejected rather than guessed.
    { cat "$work/example.service"; printf '\n[Service]\n%s\n' "$directive"; } > "$work/bad.service"
    if sh "$helper" openrc "$work/rejected" "$work/bad.service" > "$work/error" 2>&1; then
        echo "Accepted unsupported directive: $directive" >&2; exit 1
    fi
    [ ! -d "$work/rejected/etc/init.d" ]
done
printf '[Path]\nPathExists=/tmp/pending\n' > "$work/example.path"
sh "$helper" systemd "$work/systemd" "$work/example.path"
if sh "$helper" openrc "$work/mixed" "$work/example.service" "$work/example.path" > "$work/error" 2>&1; then exit 1; fi
[ ! -d "$work/mixed/etc/init.d" ]
if sh "$helper" unknown "$work/unknown" "$work/example.service" > "$work/error" 2>&1; then exit 1; fi
echo 'PASS: systemd originals, OpenRC foreground tracking, unsupported-directive rejection, no partial unit set'
