#! /bin/bash
set -euo pipefail

UPDATE_DIR="/etc/vega/update"

log_info() {
	echo "$1" | systemd-cat -t vega-update -p info
}

log_warning() {
	echo "$1" | systemd-cat -t vega-update -p warning
}

log_error() {
	echo "$1" | systemd-cat -t vega-update -p err
}

# Empty the handoff directory on EVERY exit -- success OR failure.
#
# dakupdate.path triggers this service via DirectoryNotEmpty=/etc/vega/update/.
# A path unit re-checks that condition each time the service exits: if a
# rejected or failed .deb is left behind, the directory is still non-empty, so
# systemd immediately re-triggers the service. It aborts again, re-triggers
# again... within a second this trips the start-rate limiter and the PATH unit
# dies with 'unit-start-limit-hit' -- after which NO update (USB or remote, dev
# or production) is ever detected again until reboot. Clearing the payload here
# guarantees the trigger condition clears so the watcher returns cleanly to idle
# no matter how this script exits (blocked update, corrupt package, dpkg/preinst
# failure, etc.). On success the installed package no longer needs the payload.
tmpdir=""
cleanup() {
	rm -f "${UPDATE_DIR}"/* 2>/dev/null || true
	[ -n "${tmpdir}" ] && rm -rf "${tmpdir}" 2>/dev/null || true
}
trap cleanup EXIT

shopt -s nullglob
debs=("${UPDATE_DIR}"/*.deb)
shopt -u nullglob

if [ "${#debs[@]}" -eq 0 ]; then
	log_warning "No .deb files found in ${UPDATE_DIR}; nothing to install"
	exit 0
fi

if [ "${#debs[@]}" -gt 1 ]; then
	log_error "Multiple .deb files found in ${UPDATE_DIR}; aborting to avoid ambiguous install"
	exit 1
fi

deb="${debs[0]}"
tmpdir="$(mktemp -d)"

if ! dpkg-deb --control "${deb}" "${tmpdir}" >/dev/null 2>&1; then
	log_error "Failed to inspect package control metadata: ${deb}"
	exit 1
fi

preinst_path="${tmpdir}/preinst"
if [ -f "${preinst_path}" ] && grep -Eq '^[[:space:]]*IS_PRODUCTION="?ON"?[[:space:]]*$' "${preinst_path}"; then
	if [ -f "/home/daktronics/.dev-env" ]; then
		log_error "Aborting update before dpkg: production package detected while /home/daktronics/.dev-env exists"
		echo "ERROR: Update blocked. Production package cannot be installed while /home/daktronics/.dev-env exists." >&2
		exit 1
	fi
fi

log_info "Preflight checks passed for ${deb}; starting dpkg install"
dpkg -i "${deb}"

# Payload removal is handled by the EXIT trap (cleanup), which runs on success
# AND on every failure path -- so the dakupdate.path trigger condition always
# clears and the path unit can never re-trigger this service in a loop.
