#!/usr/bin/env bash

MODULE_DOCKER_ENGINE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_DOCKER_ENGINE_PROJECT_ROOT="$(cd "$MODULE_DOCKER_ENGINE_DIR/../../.." && pwd)"

# shellcheck source=lib/package.sh
source "$MODULE_DOCKER_ENGINE_PROJECT_ROOT/lib/package.sh"
# shellcheck source=lib/system.sh
source "$MODULE_DOCKER_ENGINE_PROJECT_ROOT/lib/system.sh"
# shellcheck source=modules/containers/docker-engine/config.sh
source "$MODULE_DOCKER_ENGINE_DIR/config.sh"
# shellcheck source=modules/containers/docker-engine/metadata.conf
source "$MODULE_DOCKER_ENGINE_DIR/metadata.conf"

module_docker_engine_metadata() {
  printf '%s|%s|%s\n' "$MODULE_ID" "$MODULE_NAME" "$MODULE_DESCRIPTION"
}

module_docker_engine_remove_conflicts() {
  local packages=(docker.io docker-doc docker-compose podman-docker containerd runc)
  local pkg=""

  for pkg in "${packages[@]}"; do
    if package_is_installed "$pkg"; then
      package_remove "$pkg"
    fi
  done
}

module_docker_engine_install() {
  local target_user="${1:-$POSTINSTALL_DOCKER_TARGET_USER}"
  local data_dir="${2:-/home/$target_user/docker}"
  local version_codename=""
  local arch=""

  package_refresh_indexes
  package_install ca-certificates curl
  install -m 0755 -d "$POSTINSTALL_DOCKER_KEYRING_DIR"
  curl -fsSL https://download.docker.com/linux/debian/gpg -o "$POSTINSTALL_DOCKER_KEYRING_FILE"
  chmod a+r "$POSTINSTALL_DOCKER_KEYRING_FILE"

  version_codename="$(. /etc/os-release && printf '%s' "$VERSION_CODENAME")"
  arch="$(dpkg --print-architecture)"
  printf 'deb [arch=%s signed-by=%s] https://download.docker.com/linux/debian %s stable\n' "$arch" "$POSTINSTALL_DOCKER_KEYRING_FILE" "$version_codename" > "$POSTINSTALL_DOCKER_SOURCES_FILE"

  module_docker_engine_remove_conflicts
  package_refresh_indexes
  package_install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

  if ! system_group_exists docker; then
    groupadd docker
  fi

  if system_user_exists "$target_user" && ! system_user_in_group "$target_user" docker; then
    usermod -aG docker "$target_user"
  fi

  mkdir -p "$data_dir"
  if system_user_exists "$target_user"; then
    chown "$target_user:$target_user" "$data_dir"
  fi

  systemctl enable --now docker
  systemctl restart docker

  log_info "Docker Engine installe pour $target_user"
  ui_success "Docker Engine installe"
}

module_docker_engine_test() {
  command -v docker >/dev/null 2>&1 || return 1
  docker --version >/dev/null 2>&1 || return 1
  docker compose version >/dev/null 2>&1 || return 1
}
