#!/bin/bash

resticInstall()
{
    if command -v restic >/dev/null 2>&1; then
        local installed_version
        installed_version=$(restic version 2>/dev/null | head -1 | awk '{print $2}')
        isNotice "restic already installed (version: $installed_version)"
        return 0
    fi

    isHeader "Installing restic"

    if command -v apt-get >/dev/null 2>&1; then
        sudo apt-get update -qq >/dev/null
        if sudo apt-get install -y restic >/dev/null 2>&1; then
            checkSuccess "restic installed via apt"
            sudo restic self-update >/dev/null 2>&1 || true
            return 0
        fi
    elif command -v dnf >/dev/null 2>&1; then
        sudo dnf install -y restic && return 0
    elif command -v pacman >/dev/null 2>&1; then
        sudo pacman -S --noconfirm restic && return 0
    fi

    isNotice "Package manager install unavailable — downloading restic binary"
    local arch
    arch=$(uname -m)
    case "$arch" in
        x86_64) arch=amd64 ;;
        aarch64) arch=arm64 ;;
        armv7l) arch=arm ;;
        *) isError "Unsupported architecture: $arch"; return 1 ;;
    esac

    local tmp
    tmp=$(mktemp -d)
    if curl -sL "https://github.com/restic/restic/releases/latest/download/restic_linux_${arch}.bz2" -o "$tmp/restic.bz2"; then
        bunzip2 "$tmp/restic.bz2"
        sudo install -m 0755 "$tmp/restic" /usr/local/bin/restic
        rm -rf "$tmp"
        checkSuccess "restic installed to /usr/local/bin/restic"
    else
        rm -rf "$tmp"
        isError "Failed to download restic"
        return 1
    fi
}
