#!/bin/bash

# Kopia adapter — env + URI helpers. Kopia doesn't have a unified URI; it
# selects storage via `repository create <type>` flags. We persist that
# selection in a per-location config file (KOPIA_CONFIG_PATH) so subsequent
# commands always know which repo they're talking to.

kopiaConfigPath()
{
    local idx="$1"
    backupLocationKopiaConfig "$idx"
}

kopiaLocationUri()
{
    local idx="$1"
    # Display-only URI for the dashboard / locations row.
    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 "sftp://${user}@${host}:${port}/${path#/}"
            ;;
        *)
            isNotice "Kopia adapter currently supports local + sftp. For $t, switch the location to a different engine."
            return 1
            ;;
    esac
}

kopiaEnvExport()
{
    local idx="$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
    backupLocationEnsureDir "$idx"
    local cfg
    cfg=$(kopiaConfigPath "$idx")

    export KOPIA_PASSWORD="$pass"
    export KOPIA_CONFIG_PATH="$cfg"
    export KOPIA_CHECK_FOR_UPDATES=false
}

kopiaEnvUnset()
{
    unset KOPIA_PASSWORD KOPIA_CONFIG_PATH KOPIA_CHECK_FOR_UPDATES
}
