#!/bin/bash

## Copyright (C) 2012 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail
shopt -s inherit_errexit
shopt -s shift_verbose

# shellcheck source=./has.sh
source "${HELPER_SCRIPTS_PATH:-}"/usr/libexec/helper-scripts/has.sh

has start-stop-daemon
has timeout
has apt-get

export LC_ALL=C
pidfile="/run/helper-scripts/apt-get-update-pid"

# shellcheck disable=SC2317  # reached via the SIGTERM/SIGINT trap, not a direct call
sigterm_trap() {
   /usr/libexec/helper-scripts/apt-get-update-kill-helper &>/dev/null
   exit 143
}

## terminate potential previous invocations.
/usr/libexec/helper-scripts/apt-get-update-kill-helper &>/dev/null

trap "sigterm_trap" SIGTERM SIGINT

[[ -v timeout_after ]] || timeout_after="600"
[[ -v kill_after ]] || kill_after="10"

start-stop-daemon \
  --make-pidfile \
  --pidfile "${pidfile}" \
  --exec /usr/bin/timeout \
  --start \
  -- \
    --kill-after="${kill_after}" \
    "${timeout_after}" \
      apt-get-noninteractive update --error-on=any "$@" &

lastpid="$!"
wait "${lastpid}"

exit "$?"
