#!/bin/bash

webuiGenerateBackupPasswords()
{
    local output_dir="$containers_dir/libreportal/frontend/data/backup/generated"
    local output_file="$output_dir/passwords.txt"
    local temp_file="${output_file}.tmp.$$"

    runFileOp mkdir -p "$output_dir"

    local generated_at
    generated_at=$(date -Iseconds)
    local host="${CFG_INSTALL_NAME:-libreportal}"

    {
        echo "# LibrePortal — Backup Repository Passwords"
        echo "# Host:       $host"
        echo "# Generated:  $generated_at"
        echo "#"
        echo "# These are the encryption keys for your backup repositories. Without"
        echo "# them, the snapshots stored at each location cannot be decrypted."
        echo "# Keep this file offline (a password manager, printout, USB stick)."
        echo ""

        local idx
        while IFS= read -r idx; do
            [[ -z "$idx" ]] && continue
            local name pass
            name=$(resticLocationName "$idx")
            pass=$(resticLocationPassword "$idx")
            [[ -z "$pass" ]] && continue
            echo "# Location $idx — $name"
            echo "CFG_BACKUP_LOC_${idx}_PASSWORD=${pass}"
            echo ""
        done < <(resticAllLocationIndices)
    } | runFileWrite "$output_file"
    runFileOp chmod 0600 "$output_file"
}
