#!/usr/bin/env bash

# omarchy:summary=Install Docker Engine with Podman, Buildah and Trivy
# omarchy:requires-sudo=true

# Based: Docker Engine from Docker's own apt repository, the one upstream
# archive a Based image keeps, so a dev edition already has it and this row
# adds the rest; a system without it gets the same source. Podman, Buildah
# and the credential helpers come from apt, Trivy from its own repository.
# A Mac takes Docker Desktop with brew's podman, podman-compose and trivy;
# podman there still wants podman machine init.

set -eo pipefail

echo "Installing Docker..."

case $(omarchy-os) in
darwin)
  omarchy-pkg-add docker-desktop cask=docker-desktop podman podman-compose trivy
  ;;
*)
  if omarchy-pkg-missing docker-ce; then
    codename=$(. /etc/os-release && echo "${VERSION_CODENAME:-}")
    distro=$(. /etc/os-release && case " ${ID:-} ${ID_LIKE:-} " in *" ubuntu "*) echo ubuntu ;; *) echo debian ;; esac)
    sudo install -d -m 755 /etc/apt/keyrings
    if [[ ! -f /etc/apt/keyrings/docker.asc ]]; then
      sudo curl -fsSL "https://download.docker.com/linux/$distro/gpg" -o /etc/apt/keyrings/docker.asc
    fi
    if [[ ! -f /etc/apt/sources.list.d/docker.list ]]; then
      echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$distro $codename stable" | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null
    fi
    sudo apt-get update
    omarchy-pkg-add docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
    sudo usermod -aG docker "$USER"
  fi

  omarchy-pkg-add podman podman-compose buildah golang-docker-credential-helpers pass

  if omarchy-pkg-missing trivy; then
    sudo install -d -m 755 /etc/apt/keyrings
    curl -fsSL https://aquasecurity.github.io/trivy-repo/deb/public.key | sudo tee /etc/apt/keyrings/trivy.asc >/dev/null
    echo "deb [signed-by=/etc/apt/keyrings/trivy.asc] https://aquasecurity.github.io/trivy-repo/deb generic main" | sudo tee /etc/apt/sources.list.d/trivy.list >/dev/null
    sudo apt-get update
    omarchy-pkg-add trivy
  fi
  ;;
esac

omarchy-code-extensions ms-azuretools.vscode-docker ms-vscode-remote.remote-containers
