#!/usr/bin/env bash
set -euo pipefail

GO_VERSION="${GO_VERSION:-1.25.0}"
NODE_MAJOR="${NODE_MAJOR:-20}"

need_cmd() {
  command -v "$1" >/dev/null 2>&1
}

sudo dnf install -y \
  alsa-lib \
  atk \
  at-spi2-atk \
  at-spi2-core \
  cairo \
  cups-libs \
  dbus-libs \
  expat \
  git \
  glib2 \
  jq \
  nginx \
  gcc \
  gcc-c++ \
  libdrm \
  libgcc \
  libX11 \
  libXcomposite \
  libXdamage \
  libXext \
  libXfixes \
  libXrandr \
  libxcb \
  libxkbcommon \
  make \
  mesa-libgbm \
  nspr \
  nss \
  nss-util \
  pango \
  python3-pip \
  systemd-libs \
  tar \
  gzip \
  mariadb105

# Seed application uses the python3 selected by the workflow PATH. A distro
# python3-pip package can target a different interpreter when /usr/local/bin
# precedes /usr/bin, so verify and, if necessary, bootstrap pip for that exact
# interpreter without fetching an installer from the network.
if ! python3 -m pip --version >/dev/null 2>&1; then
  python3 -m ensurepip --upgrade --user || {
    echo "unable to bootstrap pip for $(command -v python3)" >&2
    exit 1
  }
fi
python3 -m pip --version >/dev/null 2>&1 || {
  echo "unable to provision pip for $(command -v python3)" >&2
  exit 1
}

if ! need_cmd node; then
  curl -fsSL "https://rpm.nodesource.com/setup_${NODE_MAJOR}.x" | sudo bash -
  sudo dnf install -y nodejs
fi

current_go_version=""
if need_cmd go; then
  current_go_version="$(go version | awk '{print $3}' | sed 's/^go//')"
fi

if [[ "${current_go_version}" != "${GO_VERSION}" ]]; then
  tmp_dir="$(mktemp -d)"
  trap 'rm -rf "${tmp_dir}"' EXIT
  curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o "${tmp_dir}/go.tgz"
  sudo rm -rf /usr/local/go
  sudo tar -C /usr/local -xzf "${tmp_dir}/go.tgz"
  if ! grep -q '/usr/local/go/bin' "${HOME}/.bash_profile" 2>/dev/null; then
    printf '\nexport PATH="/usr/local/go/bin:$PATH"\n' >> "${HOME}/.bash_profile"
  fi
  export PATH="/usr/local/go/bin:$PATH"
fi

sudo systemctl enable nginx

echo "host prerequisites installed"
