#!/usr/bin/env bash

function is-installed() {
  type "${1}"
}

function start-docker() {
  is-installed "systemctl" || return $?
  is-installed "docker" || return $?

  res="$(systemctl show --property ActiveState docker)" || return $?
  case "${res}" in
    "ActiveState=active")
      # Docker service is active
      true
      ;;
    "ActiveState=inactive")
      # Docker service is inactive -> Let's start it
      echo "Starting docker service ..."
      sudo systemctl start docker || return $?
      sleep 5s
      ;;
    *)
      echo "Unknown state or error!"
      return 1
  esac
}

function build-pkg() {
  # --rm: Remove container after run.
  COMPOSE_ARGS=('run' '--rm' 'makepkg')
  if [ "${INTERACTIVE}" = "true" ]; then
      COMPOSE_ARGS+=('interactive')
  fi
  COMPOSE_ARGS+=("${1}")

  sudo docker-compose "${COMPOSE_ARGS[@]}"
}

function push-pkg() {
  arch-repo-push-new || return $?  # Push remote repository
}

function build-and-push() {
  for PKG in "$@"; do
    build-pkg "${PKG}" || return $?
  done
  push-pkg || return $?
}

function space_separated_to_array() {
  # arg $1: name of variable with space separated list
  # arg $2: name of array to store values into

  local -n ptr=$1  || return $?
  local -n ptr2=$2 || return $?
  # ptr space separated list.
  # Store this as array ptr2.
  # Without newline at last array element: https://unix.stackexchange.com/a/519917/315162
  # shellcheck disable=SC2034
  readarray -d " " -t ptr2 < <(printf '%s' "$ptr")
}

function main() {
  start-docker || return $?
  is-installed "docker-compose" || return $?

  if [ "${1}" = "interactive" ]; then
    echo "Interactive mode enabled"
    INTERACTIVE=true
    shift;  # remove first argument
  fi

  PKGLIST=pkglist-AUR.txt  # TODO
  mapfile -t STAGES < "${PKGLIST}"
  # shellcheck disable=SC2034
  for line in "${STAGES[@]}"; do
    space_separated_to_array line pkgs
    # shellcheck disable=SC2154
    build-and-push "${pkgs[@]}" || exit $?
  done

  echo "Successfully built all packages!"
}

main "$@"
