#!/bin/sh
# SSH_ASKPASS helper: prints the Aspire password on stdout for ssh to consume.
#
# Never invoke this directly. ssh calls it when SSH_ASKPASS_REQUIRE=force is set
# (see aspire-connect). The prompt text ssh is asking about arrives as $1.

set -eu

CRED="${ASPIRE_CRED:-$HOME/.config/aspire/password}"

# ssh routes *every* interactive prompt here, not just password ones. Refuse
# anything that looks like host-key verification so we never answer a
# "yes/no" question with the password.
prompt="${1:-}"
case "$prompt" in
    *yes/no*|*fingerprint*|*"Are you sure"*)
        echo "aspire-askpass: refusing non-password prompt: $prompt" >&2
        exit 1
        ;;
esac

if [ ! -f "$CRED" ]; then
    echo "aspire-askpass: no credential file at $CRED" >&2
    echo "aspire-askpass: run bin/aspire-setup-credentials to create it" >&2
    exit 1
fi

# Refuse to read a world/group-readable secret.
perms=$(ls -l "$CRED" | cut -c5-10)
case "$perms" in
    ------) ;;
    *)
        echo "aspire-askpass: $CRED is group/world readable; run: chmod 600 $CRED" >&2
        exit 1
        ;;
esac

# First line only, so a stray trailing newline in the file is harmless.
IFS= read -r password < "$CRED" || true

if [ -z "$password" ]; then
    echo "aspire-askpass: $CRED is empty" >&2
    exit 1
fi

printf '%s\n' "$password"
