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

CONFIG="${IPCO_FIRSTBOOT_CONFIG:-/etc/ipco/firstboot.conf}"
STATE_DIR="${IPCO_FIRSTBOOT_STATE_DIR:-/var/lib/ipco}"
DONE="$STATE_DIR/firstboot.done"
PACKAGES="${IPCO_FIRSTBOOT_PACKAGES:-k3-scheduler k3-scheduler-platform-k3 rv-sherpa-onnx-runtime attune-server attune-oss-companion attune-web-demo}"
APT_UPDATE="${IPCO_FIRSTBOOT_APT_UPDATE:-1}"

if [ -f "$CONFIG" ] && [ ! -L "$CONFIG" ]; then
  # shellcheck source=/dev/null
  . "$CONFIG"
  PACKAGES="${IPCO_FIRSTBOOT_PACKAGES:-$PACKAGES}"
  APT_UPDATE="${IPCO_FIRSTBOOT_APT_UPDATE:-$APT_UPDATE}"
fi

case "$APT_UPDATE" in 0|1) ;; *)
  printf 'ipco-firstboot: IPCO_FIRSTBOOT_APT_UPDATE must be 0 or 1\n' >&2
  exit 2
  ;;
esac
if [ -z "${PACKAGES//[[:space:]]/}" ]; then
  printf 'ipco-firstboot: IPCO_FIRSTBOOT_PACKAGES is empty\n' >&2
  exit 2
fi

[ ! -e "$DONE" ] || {
  printf 'ipco-firstboot: already completed: %s\n' "$DONE"
  exit 0
}

if [ "$APT_UPDATE" = 1 ]; then
  apt-get update
fi

read -r -a package_list <<<"$PACKAGES"
apt-get install -y --no-install-recommends "${package_list[@]}"

install -d -m 0755 "$STATE_DIR"
{
  printf 'completed_at=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  printf 'packages=%s\n' "$PACKAGES"
} >"$DONE"
chmod 0644 "$DONE"
if command -v systemctl >/dev/null 2>&1; then
  systemctl disable ipco-firstboot.service >/dev/null 2>&1 || true
fi
printf 'ipco-firstboot: completed packages=%s\n' "$PACKAGES"
