#!/bin/bash

kopiaInstall()
{
    if command -v kopia >/dev/null 2>&1; then
        local v
        v=$(kopia --version 2>/dev/null | head -1)
        isNotice "Kopia already installed ($v)"
        return 0
    fi

    isHeader "Installing Kopia backup engine"

    local arch
    arch=$(uname -m)
    case "$arch" in
        x86_64)  arch=x64 ;;
        aarch64) arch=arm64 ;;
        armv7l)  arch=arm ;;
        *) isError "Unsupported architecture for Kopia: $arch"; return 1 ;;
    esac

    local version url tmp
    version=$(curl -sL https://api.github.com/repos/kopia/kopia/releases/latest 2>/dev/null \
        | grep -oE '"tag_name":\s*"v[0-9.]+"' | head -1 | grep -oE '[0-9.]+')
    if [[ -z "$version" ]]; then
        isError "Could not look up the latest Kopia release. Install manually (https://kopia.io/) and re-run init."
        return 1
    fi

    url="https://github.com/kopia/kopia/releases/download/v${version}/kopia-${version}-linux-${arch}.tar.gz"
    tmp=$(mktemp -d)
    if ! curl -sL "$url" -o "$tmp/kopia.tgz"; then
        rm -rf "$tmp"
        isError "Failed to download Kopia v${version} for ${arch}"
        return 1
    fi

    sudo tar xzf "$tmp/kopia.tgz" -C "$tmp"
    local bin
    bin=$(find "$tmp" -name kopia -type f -executable | head -1)
    if [[ -z "$bin" ]]; then
        rm -rf "$tmp"
        isError "Kopia binary not found in archive"
        return 1
    fi
    sudo install -m 0755 "$bin" /usr/local/bin/kopia
    rm -rf "$tmp"
    checkSuccess "Kopia v${version} installed to /usr/local/bin/kopia"
}
