#!/bin/sh
# C2-03a: git's GIT_ASKPASS for library sync (packages/library/src/sync.mjs). It answers only the
# Username and Password prompts for the configured host and user, and exits 1 on anything else.
# The env names the slot path, never the token. printf is a shell builtin, so the token is in no argv.
# C2-03b: the slot is whichever file the bus chose (a grant store file, library-gitea or library-human),
# read with readSecretFile's checks (gitea-grant.mjs): a regular file the bus's uid owns, mode 0600, at
# most 16384 bytes. The checks run on the open fd 3, and its dev:inode must match the path's own
# (an lstat), so a link or a swap before the open refuses and the token comes from the checked file
# (dewey-0860). Residual, as in readSecretFile: a FIFO swapped in after test -f blocks the open.
host=$MOSAIC_LIBRARY_HOST user=$MOSAIC_LIBRARY_USER slot=$MOSAIC_LIBRARY_SLOT
test -n "$host" && test -n "$user" && test -n "$slot" || exit 1
case $host in *[!a-z0-9.:-]*) exit 1 ;; esac
case $user in *[!A-Za-z0-9_.-]*) exit 1 ;; esac
case $1 in
  "Username for 'https://$host': ") printf '%s\n' "$user" ;;
  "Password for 'https://$user@$host': ")
    test -f "$slot" && test ! -L "$slot" || exit 1
    exec 3<"$slot" || exit 1
    open=$(stat -L -c '%d:%i %u %a %s %F' /dev/fd/3 2>/dev/null) || exit 1
    path=$(stat -c '%d:%i' -- "$slot" 2>/dev/null) || exit 1
    set -- $open
    test "$1" = "$path" && test "$2" = "$(id -u)" && test "$3" = 600 && test "$4" -le 16384 \
      && test "$5 $6" = "regular file" && test $# -eq 6 || exit 1
    IFS= read -r token <&3 || test -n "$token" || exit 1
    exec 3<&-
    test -n "$token" || exit 1
    printf '%s\n' "$token" ;;
  *) exit 1 ;;
esac
