#!/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

command -v start-stop-daemon >/dev/null
command -v timeout >/dev/null
command -v apt-get >/dev/null

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

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 "$?"
