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

readonly dockerKeyring="/etc/apt/keyrings/docker.asc"
readonly dockerSources="/etc/apt/sources.list.d/docker.list"

dockerIsInstalled() {
    util::cmdExists docker
}

dockerRepositoryIsConfigured() {
    [[ -f "$dockerSources" ]]
}

userIsInDockerGroup() {
    groups "$USER" | grep -qw docker
}

lazydockerIsInstalled() {
    util::cmdExists lazydocker
}

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

addDockerSigningKey() {
    sudo install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
        | sudo tee "$dockerKeyring" > /dev/null
    sudo chmod a+r "$dockerKeyring"
    log::ok "Clave GPG de Docker instalada"
}

addDockerRepository() {
    local ubuntuCodename
    ubuntuCodename="$(. /etc/os-release && echo "$VERSION_CODENAME")"
    echo "deb [arch=amd64 signed-by=${dockerKeyring}] https://download.docker.com/linux/ubuntu ${ubuntuCodename} stable" \
        | sudo tee "$dockerSources" > /dev/null
    sudo apt-get update -qq
    log::ok "Repositorio Docker configurado para Ubuntu ${ubuntuCodename}"
}

installDockerPackages() {
    sudo apt-get install -y \
        docker-ce \
        docker-ce-cli \
        containerd.io \
        docker-buildx-plugin \
        docker-compose-plugin
    log::ok "Docker Engine y Docker Compose instalados"
}

addUserToDockerGroup() {
    sudo usermod -aG docker "$USER"
    log::ok "Usuario $USER agregado al grupo docker"
    log::info "Cerrá sesión y volvé a entrar para usar Docker sin sudo"
}

installLazydocker() {
    local version versionNumber temporaryDirectory
    version="$(latestGithubReleaseTag "jesseduffield/lazydocker")"
    versionNumber="${version#v}"
    temporaryDirectory="$(mktemp -d)"
    trap 'rm -rf "$temporaryDirectory"' RETURN
    curl -fsSL \
        "https://github.com/jesseduffield/lazydocker/releases/download/${version}/lazydocker_${versionNumber}_Linux_x86_64.tar.gz" \
        | tar -xz -C "$temporaryDirectory"
    mkdir -p "$HOME/.local/bin"
    mv "$temporaryDirectory/lazydocker" "$HOME/.local/bin/lazydocker"
    log::ok "Lazydocker ${version} instalado en ~/.local/bin/"
}

if dockerIsInstalled; then
    log::info "Docker ya instalado: $(docker --version)"
else
    log::info "Instalando Docker Engine..."
    util::requireSudo
    if ! dockerRepositoryIsConfigured; then
        addDockerSigningKey
        addDockerRepository
    fi
    installDockerPackages
fi

if userIsInDockerGroup; then
    log::info "Usuario $USER ya en el grupo docker"
else
    util::requireSudo
    addUserToDockerGroup
fi

if lazydockerIsInstalled; then
    log::info "Lazydocker ya instalado"
else
    installLazydocker
fi
