#!/bin/bash

kopiaInitLocation()
{
    local idx="$1"

    if ! resticLocationEnabled "$idx"; then
        isNotice "Location $(resticLocationName "$idx") disabled — skipping init"
        return 0
    fi

    kopiaEnvExport "$idx" || return 1

    local t
    t=$(resticLocationType "$idx")

    # Already initialized? `kopia repository status` returns 0 only if the
    # config file is connected to a repo.
    if runBackupOp kopia repository status --json >/dev/null 2>&1; then
        isNotice "$(resticLocationName "$idx") already initialized"
        kopiaEnvUnset
        return 0
    fi

    local args
    case "$t" in
        local)
            local path
            path=$(backupLocationResolvedPath "$idx")
            runFileOp mkdir -p "$path"
            runFileOp chown -R "$docker_install_user":"$docker_install_user" "$path"
            args=(repository create filesystem --path="$path")
            ;;
        sftp)
            local user host port path auth keyfile
            user=$(resticLocationField "$idx" SSH_USER)
            host=$(resticLocationField "$idx" SSH_HOST)
            port=$(resticLocationField "$idx" SSH_PORT)
            [[ -z "$port" ]] && port=22
            path=$(resticLocationField "$idx" SSH_PATH)
            auth=$(resticLocationField "$idx" SSH_AUTH)
            if [[ "$auth" == "password" ]]; then
                isError "Kopia's SFTP backend supports key auth only. Switch this location's engine to restic or borg if you need password auth, or generate an SSH key on the location's edit panel."
                kopiaEnvUnset
                return 1
            fi
            keyfile=$(backupSshKeyFile "$idx")
            if [[ ! -f "$keyfile" ]]; then
                isError "Kopia SFTP needs a private key at $keyfile — generate or paste one on the location's edit panel."
                kopiaEnvUnset
                return 1
            fi
            args=(repository create sftp --host="$host" --port="$port" --username="$user" --path="$path" --known-hosts-data="" --keyfile="$keyfile")
            ;;
        *)
            isError "Kopia adapter doesn't support type=$t yet"
            kopiaEnvUnset
            return 1
            ;;
    esac

    isNotice "Initializing $(resticLocationName "$idx") with Kopia"
    if runBackupOp kopia "${args[@]}"; then
        isSuccessful "$(resticLocationName "$idx") initialized"
    else
        isError "Failed to initialize $(resticLocationName "$idx") with Kopia"
        kopiaEnvUnset
        return 1
    fi

    kopiaEnvUnset
}

kopiaEnsureLocationReady()
{
    local idx="$1"
    [[ -z "$idx" ]] && return 1

    if ! resticLocationEnabled "$idx"; then
        return 1
    fi

    local cfg
    cfg=$(kopiaConfigPath "$idx")
    if [[ -f "$cfg" ]]; then
        return 0
    fi

    if ! command -v kopia >/dev/null 2>&1; then
        kopiaInstall || return 1
    fi
    kopiaInitLocation "$idx"
}
