#!/usr/bin/env bash
# Both-ways proof that no environment.d conf carries a systemd unit specifier.
# environment.d is read by systemd-environment-d-generator and re-sourced by
# remote-runner.sh with `set -a`; neither expands `%h`, both expand `${HOME}`.
# A literal `%h` therefore reaches every build job as a relative path and gets
# created under whatever the job's working directory happens to be.
set -uo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
PASS=0; FAIL=0
ok() { PASS=$((PASS+1)); printf 'ok   %s\n' "$1"; }
no() { FAIL=$((FAIL+1)); printf 'FAIL %s\n     %s\n' "$1" "$2"; }

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

# Reports every `%<specifier>` occurrence in the given conf files; empty output = clean.
scan() {
  local f
  for f in "$@"; do
    [ -r "$f" ] || continue
    grep -Hn '%[a-zA-Z%]' "$f"
  done
}

printf 'PYTHONPYCACHEPREFIX=%%h/.cache/python-bytecode\n' > "$TMP/bad.conf"
printf 'PYTHONPYCACHEPREFIX=${HOME}/.cache/python-bytecode\n' > "$TMP/good.conf"

out=$(scan "$TMP/bad.conf")
[[ -n "$out" ]] \
  && ok "unexpanded %h in an environment.d conf is rejected" \
  || no "unexpanded %h in an environment.d conf is rejected" "scan found nothing"

out=$(scan "$TMP/good.conf")
[[ -z "$out" ]] \
  && ok "\${HOME} form accepted" \
  || no "\${HOME} form accepted" "$out"

# The value a shell sourcer produces must be an absolute path, not a relative one.
val=$(set -a; . "$TMP/good.conf"; set +a; printf '%s' "$PYTHONPYCACHEPREFIX")
[[ "$val" == /* ]] \
  && ok "\${HOME} form sources to an absolute path" \
  || no "\${HOME} form sources to an absolute path" "got $val"

val=$(set -a; . "$TMP/bad.conf"; set +a; printf '%s' "$PYTHONPYCACHEPREFIX")
[[ "$val" != /* ]] \
  && ok "%h form is proven relative when sourced by a shell" \
  || no "%h form is proven relative when sourced by a shell" "got $val"

mapfile -t repo_confs < <(find "$ROOT/modules" -path '*/environment.d/*.conf' -type f 2>/dev/null)
out=$(scan "${repo_confs[@]}")
[[ -z "$out" ]] \
  && ok "repo environment.d confs free of unit specifiers (${#repo_confs[@]} files)" \
  || no "repo environment.d confs free of unit specifiers" "$out"

if [[ -d "$HOME/.config/environment.d" ]]; then
  out=$(scan "$HOME"/.config/environment.d/*.conf)
  [[ -z "$out" ]] \
    && ok "installed environment.d confs free of unit specifiers" \
    || no "installed environment.d confs free of unit specifiers" "$out"
fi

printf 'environment-d-specifiers.test: PASS=%d FAIL=%d\n' "$PASS" "$FAIL"
[[ "$FAIL" -eq 0 ]]
