#!/bin/bash

# Build the SSH command engines use to reach an SFTP location. Honours
# CFG_BACKUP_LOC_N_SSH_AUTH:
#   - "key" (default):    plain `ssh ... -s sftp` / `ssh ...`
#   - "password":         exports SSHPASS=<pass> and prefixes with `sshpass -e`
#
# Args:
#   idx     — location index
#   port    — SSH port
#   mode    — "sftp" (append `-s sftp`) or "raw" (just the ssh prefix, no -s)
#
# Echoes the command on stdout. Returns non-zero with an isError if password
# mode is requested without sshpass on PATH.

backupSshCommand()
{
    local idx="$1"
    local port="${2:-22}"
    local mode="${3:-raw}"

    local auth pass
    auth=$(resticLocationField "$idx" SSH_AUTH)
    pass=$(resticLocationField "$idx" SSH_PASS)
    [[ -z "$auth" ]] && auth=key

    local base="ssh -p $port -o StrictHostKeyChecking=accept-new"
    [[ "$mode" == "sftp" ]] && local suffix=" -s sftp" || local suffix=""

    if [[ "$auth" == "password" ]]; then
        if [[ -z "$pass" ]]; then
            isError "Location $idx is set to password auth but CFG_BACKUP_LOC_${idx}_SSH_PASS is empty"
            return 1
        fi
        if ! command -v sshpass >/dev/null 2>&1; then
            isError "sshpass not installed but location $idx uses password auth — apt install sshpass"
            return 1
        fi
        export SSHPASS="$pass"
        echo "sshpass -e $base -o PreferredAuthentications=password -o PubkeyAuthentication=no${suffix}"
    else
        # Key mode: when LibrePortal has a per-location key, pin -i and force
        # identities-only so the right key is used; otherwise fall back to
        # whatever the docker_install_user has configured.
        local key_file=""
        if declare -f backupSshKeyFile >/dev/null 2>&1; then
            key_file=$(backupSshKeyFile "$idx")
        fi
        if [[ -n "$key_file" && -f "$key_file" ]]; then
            echo "$base -i $key_file -o IdentitiesOnly=yes${suffix}"
        else
            echo "$base${suffix}"
        fi
    fi
}
