#!/bin/bash

# Armbian: apt version, or nala if installed. Install the given packages
# (Arch names are translated) when any is missing.
# As upstream: with OMARCHY_PKG_DEFER=1 and OMARCHY_PKG_QUEUE_FILE, only add
# the names to the queue file. A call with a queue file also installs the
# queued names, then empties the file.

if [[ ${OMARCHY_PKG_DEFER:-} == "1" && -n ${OMARCHY_PKG_QUEUE_FILE:-} ]]; then
  (( $# == 0 )) && exit 0
  printf '%s\n' "$@" >>"$OMARCHY_PKG_QUEUE_FILE" || exit 1
  exit 0
fi

pkgs=("$@")
flushed_queue=0
if [[ -n ${OMARCHY_PKG_QUEUE_FILE:-} && -s $OMARCHY_PKG_QUEUE_FILE ]]; then
  # grep: 1 is a queue of blank lines, 2 a queue that cannot be read.
  queue=$(grep -v '^$' "$OMARCHY_PKG_QUEUE_FILE") || (( $? == 1 )) || exit 1
  [[ -z $queue ]] || mapfile -t queued <<<"$queue"
  pkgs+=("${queued[@]}")
  flushed_queue=1
fi

if (( ${#pkgs[@]} == 0 )); then
  # A queue of blank lines: empty it too.
  (( flushed_queue )) && { : >"$OMARCHY_PKG_QUEUE_FILE" || exit 1; }
  exit 0
fi

names=$(omarchy-pkg-debname "${pkgs[@]}") || exit 1

# nala, if installed: parallel downloads.
apt=apt-get
omarchy-cmd-present nala && apt=nala
if omarchy-pkg-missing "${pkgs[@]}"; then
  if (( EUID == 0 )); then
    DEBIAN_FRONTEND=noninteractive $apt install -y -- $names || exit 1
  else
    sudo DEBIAN_FRONTEND=noninteractive $apt install -y -- $names || exit 1
  fi
fi

for pkg in "${pkgs[@]}"; do
  if ! omarchy-pkg-present "$pkg"; then
    echo -e "\033[31mError: Package '$pkg' did not install\033[0m" >&2
    exit 1
  fi
done

if (( flushed_queue )); then
  : >"$OMARCHY_PKG_QUEUE_FILE" || exit 1
fi

exit 0
