#!/bin/bash

# Emit the admin SSH-access snapshot the WebUI reads: the install user, whether
# sshd allows password login, and the list of authorized public keys (type +
# fingerprint + comment). Public keys only — never anything secret.

webuiGenerateSshAccess()
{
    local out_dir="$containers_dir/libreportal/frontend/data/ssh"
    local out_file="$out_dir/access.json"
    runFileOp mkdir -p "$out_dir"

    local jsonEscape
    jsonEscape() {
        local s="$1"
        s="${s//\\/\\\\}"; s="${s//\"/\\\"}"
        s="${s//$'\t'/ }"; s="${s//$'\r'/}"; s="${s//$'\n'/ }"
        printf '%s' "$s"
    }

    local user akf pw_auth
    user=$(declare -f hostSshUser >/dev/null 2>&1 && hostSshUser || echo "${sudo_user_name:-libreportal}")
    akf=$(declare -f hostSshAuthKeysFile >/dev/null 2>&1 && hostSshAuthKeysFile || echo "/home/$user/.ssh/authorized_keys")
    if declare -f hostSshPasswordAuthEnabled >/dev/null 2>&1 && hostSshPasswordAuthEnabled; then
        pw_auth="true"
    else
        pw_auth="false"
    fi

    local keys_json="[" first=true line type comment info fpr
    if runSshAccess has-keys; then
        while IFS= read -r line; do
            [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
            type=$(awk '{print $1}' <<< "$line")
            comment=$(awk '{ $1=""; $2=""; sub(/^[[:space:]]+/,""); print }' <<< "$line")
            info=$(printf '%s\n' "$line" | ssh-keygen -l -f - 2>/dev/null)
            [[ -z "$info" ]] && continue
            fpr=$(awk '{print $2}' <<< "$info")
            $first || keys_json+=","
            first=false
            keys_json+="{\"type\":\"$(jsonEscape "$type")\",\"fingerprint\":\"$(jsonEscape "$fpr")\",\"comment\":\"$(jsonEscape "$comment")\"}"
        done < <(runSshAccess read-keys)
    fi
    keys_json+="]"

    printf '{"generated_at":"%s","user":"%s","password_auth":%s,"keys":%s}\n' \
        "$(date -Iseconds)" "$(jsonEscape "$user")" "$pw_auth" "$keys_json" \
        | runFileWrite "$out_file"
    isSuccessful "SSH access snapshot regenerated"
}
