#!/bin/sh
# Purpose: install the .deb that unicam-hub.service handed off.
# Runs as root from unicam-hub-update.service. The package is moved to a
# root-only dir first so the service user cannot swap it mid-install and the
# path unit does not re-trigger.
set -eu

PENDING=/var/lib/unicam-hub/update/unicam-hub.deb
WORK=/var/cache/unicam-hub-update
PKG="${WORK}/unicam-hub.deb"

[ -e "${PENDING}" ] || exit 0
if [ -L "${PENDING}" ] || [ ! -f "${PENDING}" ]; then
  echo "refusing non-regular file ${PENDING}" >&2
  rm -f "${PENDING}"
  exit 1
fi

install -d -m 0700 -o root -g root "${WORK}"
cp "${PENDING}" "${PKG}"
rm -f "${PENDING}"

# apt-get resolves dependencies and waits for the dpkg lock (e.g. held by
# unattended-upgrades) instead of failing at once like dpkg -i.
apt-get install -y -o DPkg::Lock::Timeout=300 "${PKG}"
rm -f "${PKG}"
