#!/bin/bash
#
# Install prerequisites for binary distributions of Drake on Ubuntu.

set -euo pipefail

with_update=1
with_asking=1

while [ "${1:-}" != "" ]; do
  case "$1" in
    # Do NOT call apt-get update during execution of this script.
    --without-update)
      with_update=0
      ;;
    # Pass -y along to apt-get.
    -y)
      with_asking=0
      ;;
    *)
      echo 'Invalid command line argument' >&2
      exit 3
  esac
  shift
done

maybe_sudo=
if [[ "${EUID}" -ne 0 ]]; then
  maybe_sudo=sudo
fi

if [[ "${with_asking}" -eq 0 ]]; then
  maybe_yes='-y'
else
  maybe_yes=''
fi

if command -v conda &>/dev/null; then
  echo 'NOTE: Drake is not tested regularly with Anaconda, so you may experience compatibility hiccups; when asking for help, be sure to mention that Conda is involved.' >&2
fi

if [[ "${with_update}" -eq 1 ]]; then
  ${maybe_sudo} apt-get update || (sleep 30; ${maybe_sudo} apt-get update) || (cat <<EOF && false)
****************************************************************************
Drake is unable to run 'sudo apt-get update', probably because this computer
contains incorrect entries in its sources.list files, or possibly because an
internet service is down.

Run 'sudo apt-get update' and try to resolve whatever problems it reports.
Do not try to set up Drake until that command succeeds.

This is not a bug in Drake.  Do not contact the Drake team for help.
****************************************************************************
EOF
fi

. /etc/os-release

if ! [[ "${VERSION_CODENAME}" =~ (noble|resolute) ]]; then
  echo 'ERROR: This script requires Ubuntu 24.04 (Noble) or Ubuntu 26.04 (Resolute)' >&2
  exit 2
fi

packages=$(cat "${BASH_SOURCE%/*}/packages-${VERSION_CODENAME}-binary.txt")
${maybe_sudo} apt-get install ${maybe_yes} --no-install-recommends ${packages}
