#!/bin/bash

# Borg adapter — repository URI builder + env exporter. Borg uses BORG_REPO,
# BORG_PASSPHRASE, and BORG_RSH (for SFTP). Password comes straight from
# CFG_BACKUP_LOC_<idx>_PASSWORD via resticLocationPassword.

borgLocationUri()
{
    local idx="$1"
    local override
    override=$(resticLocationField "$idx" URI)
    if [[ -n "$override" ]]; then
        echo "$override"
        return
    fi

    local t
    t=$(resticLocationType "$idx")
    case "$t" in
        local)
            backupLocationResolvedPath "$idx"
            ;;
        sftp)
            local user host port path
            user=$(resticLocationField "$idx" SSH_USER)
            host=$(resticLocationField "$idx" SSH_HOST)
            port=$(resticLocationField "$idx" SSH_PORT)
            [[ -z "$port" ]] && port=22
            path=$(resticLocationField "$idx" SSH_PATH)
            echo "ssh://${user}@${host}:${port}/${path#/}"
            ;;
        *)
            # Borg doesn't natively support S3/B2/etc. — recommend rclone-mount.
            isNotice "Borg supports local + sftp natively. For $t, mount the bucket via rclone and use type=local."
            return 1
            ;;
    esac
}

borgEnvExport()
{
    local idx="$1"
    local uri
    uri=$(borgLocationUri "$idx") || return 1

    local pass
    pass=$(resticLocationPassword "$idx")
    if [[ -z "$pass" || "$pass" == RANDOMIZEDPASSWORD* ]]; then
        isError "Location $idx has no password set (CFG_BACKUP_LOC_${idx}_PASSWORD). Run the install/scan password pass first."
        return 1
    fi

    export BORG_REPO="$uri"
    export BORG_PASSPHRASE="$pass"

    if [[ "$(resticLocationType "$idx")" == "sftp" ]]; then
        local port ssh_cmd
        port=$(resticLocationField "$idx" SSH_PORT)
        [[ -z "$port" ]] && port=22
        ssh_cmd=$(backupSshCommand "$idx" "$port" "raw") || return 1
        export BORG_RSH="$ssh_cmd"
    fi
}

borgEnvUnset()
{
    unset BORG_REPO BORG_PASSPHRASE BORG_RSH SSHPASS
}

# Borg archive name template — encodes the metadata we'd otherwise put in
# restic tags. Filter on it with `borg list --glob-archives '<app>-<host>-*'`.
borgArchiveName()
{
    local app="$1"
    local host="${2:-$CFG_INSTALL_NAME}"
    local timestamp
    timestamp=$(date -u +%Y-%m-%dT%H:%M:%S)
    echo "${app}-${host}-${timestamp}"
}
