#!/usr/bin/env bash
set -euo pipefail
source "$stpRoot/lib/log.sh"
source "$stpRoot/lib/utils.sh"

latestGithubReleaseTag() {
    local repository="$1"
    curl -fsSL "https://api.github.com/repos/${repository}/releases/latest" \
        | grep '"tag_name"' \
        | cut -d'"' -f4
}

ensureBasePackagesAreInstalled() {
    local requiredPackages=(curl wget git nano gpg ca-certificates)
    local missingPackages=()

    for packageName in "${requiredPackages[@]}"; do
        util::isAptInstalled "$packageName" || missingPackages+=("$packageName")
    done

    if [[ ${#missingPackages[@]} -gt 0 ]]; then
        util::aptUpdateOnce
        sudo apt-get install -y "${missingPackages[@]}"
    fi
}

installYqFromGithub() {
    local version
    version="$(latestGithubReleaseTag "mikefarah/yq")"
    sudo wget -qO /usr/local/bin/yq \
        "https://github.com/mikefarah/yq/releases/download/${version}/yq_linux_amd64"
    sudo chmod +x /usr/local/bin/yq
    log::ok "yq ${version} instalado"
}

ensureYqIsInstalled() {
    if util::cmdExists yq; then
        log::info "yq ya disponible: $(yq --version 2>&1 | head -1)"
        return
    fi
    log::info "Instalando yq..."
    installYqFromGithub
}

ageIsAvailableInApt() {
    apt-cache show age &>/dev/null 2>&1
}

installAgeFromApt() {
    sudo apt-get install -y age
}

installAgeFromGithub() {
    local version
    version="$(latestGithubReleaseTag "FiloSottile/age")"
    local temporaryDirectory
    temporaryDirectory="$(mktemp -d)"
    trap 'rm -rf "$temporaryDirectory"' RETURN
    curl -fsSL \
        "https://github.com/FiloSottile/age/releases/download/${version}/age-${version}-linux-amd64.tar.gz" \
        | tar -xz -C "$temporaryDirectory"
    sudo mv "$temporaryDirectory/age/age" "$temporaryDirectory/age/age-keygen" /usr/local/bin/
}

ensureAgeIsInstalled() {
    if util::cmdExists age; then
        log::info "age ya disponible: $(age --version 2>&1)"
        return
    fi
    log::info "Instalando age..."
    if ageIsAvailableInApt; then
        installAgeFromApt
    else
        installAgeFromGithub
    fi
    log::ok "age instalado"
}

log::info "Verificando dependencias base"
ensureBasePackagesAreInstalled
ensureYqIsInstalled
ensureAgeIsInstalled
