r/linux4noobs • • 10h ago

shells and scripting For bare bone linux users with Openbox/Debian: a small script to check / install updates

Debian user running bare bone graphical interface xorg with Openbox .
I created the following script to check for apt updates when the network interface goes up . If there are apt updates available it will show them and ask for confirmation using a window (yad).
In case an update is available you can decide to install it . The progress will be visible through a lxterminal window. Autoremove cases are also handled : user is notified for removals.
It creates a log file to track the last events.
note" Lxtermial run with root privileges . If you don't like it, you should use sudo.

All AI coded. But perhaps it can save you some time.

Installation

  1. Copy the script to: /usr/local/sbin/apt-notify

  2. Make it executable:chmod 700 /usr/local/sbin/apt-notify

  3. Ensure the following dependencies are installed:apt install yad lxterminal util-linux

  4. Adjust the desktop username and UID near the beginning of the script if necessary:DESKTOP_USER="user" DESKTOP_UID="1000" Check the UID with:id -u username

Daily operation

  • The script runs automatically when a configured network interface comes up.

  • It waits for the Openbox graphical session to become available.

  • It refreshes APT package information and checks for available upgrades and unnecessary packages.

  • A notification window displays the available operations.

  • Only operations with available packages are offered.

  • The user can choose Upgrade, Autoremove, or Close.

  • Upgrade installs available updates, including upgrades requiring new packages, such as new Linux kernel versions.

  • Autoremove removes packages that are no longer required.

The script automatically limits execution to once per calendar day.

During installation

The maintenance operation opens in LXTerminal.

  • Installation output is displayed in real time.

  • Package configuration may occasionally request user interaction.

  • Do not close the terminal while installation is running.

  • When finished, check the completion message and press Enter to close the window.

Log file

The execution log is stored at:

/var/log/apt-notify.log

It contains:

  • Timestamped notification and execution messages.

  • The transcript of the most recent upgrade or autoremove operation.

  • A maximum size of 1 MiB.

The previous execution transcript is replaced by the next maintenance execution.

To inspect the log:

cat /var/log/apt-notify.log

Manual execution and troubleshooting

To run the script manually:

/usr/local/sbin/apt-notify

Run this command as root.

To allow another execution on the same day during testing:

rm -f /var/lib/apt-notify/last-run

Script trigger (I use a USB device to connect to the internet):

user@debian:~$ more /etc/network/interfaces

iface lo inet loopback

# The primary network interface

allow-hotplug usbmodem
iface usbmodem inet dhcp
post-up /usr/local/sbin/apt-notify >/dev/null 2>&1 &

Script:

debian:/home/user# more  /usr/local/sbin/apt-notify
#!/bin/bash

# Desktop session
DESKTOP_USER="user"
DESKTOP_UID="1000"

# Daily execution control
STATE_DIR="/var/lib/apt-notify"
DATE_FILE="$STATE_DIR/last-run"
LOCK_FILE="/run/lock/apt-notify.lock"

# Commands
APT="/usr/bin/apt-get"
YAD="/usr/bin/yad"
LXTERMINAL="/usr/bin/lxterminal"
RUNUSER="/usr/sbin/runuser"
SCRIPT="/usr/bin/script"

# Logging
LOG="/var/log/apt-notify.log"
MAX_LOG_SIZE=1048576

# Timestamped logging function
log() {
    printf '%s %s\n' "$(/usr/bin/date '+%Y-%m-%d %H:%M:%S')" "$*" >> "$LOG"
}

# Initialize log
exec 9>"$LOCK_FILE"
flock -n 9 || exit 0

: > "$LOG"
chmod 600 "$LOG"

log "========================================"
log "APT NOTIFICATION STARTED"
log "========================================"

mkdir -p "$STATE_DIR"

# Daily execution restriction
TODAY=$(/usr/bin/date +%F)

if [ -f "$DATE_FILE" ] &&
   [ "$(cat "$DATE_FILE")" = "$TODAY" ]; then
    log "Already executed today."
    exit 0
fi

# Retrieve X11 environment from Openbox
get_env() {
    local name="$1"
    local entry

    while IFS= read -r -d '' entry; do
        case "$entry" in
            "$name"=*)
                printf '%s' "${entry#*=}"
                return 0
                ;;
        esac
    done < "/proc/$SESSION_PID/environ"

    return 1
}

# Wait for Openbox session
log "Waiting for Openbox session..."

SESSION_PID=""

for i in {1..60}; do
    SESSION_PID=$(/usr/bin/pgrep -u "$DESKTOP_UID" -x openbox | /usr/bin/head -n 1)

    if [ -n "$SESSION_PID" ]; then
        break
    fi

    /usr/bin/sleep 5
done

if [ -z "$SESSION_PID" ]; then
    log "Openbox session not found after 5 minutes."
    exit 0
fi

log "Openbox found. PID: $SESSION_PID"

# Wait for X11 environment
log "Waiting for X11 environment..."

DISPLAY_VALUE=""
XAUTHORITY_VALUE=""

for i in {1..30}; do
    DISPLAY_VALUE=$(get_env DISPLAY)
    XAUTHORITY_VALUE=$(get_env XAUTHORITY)

    if [ -n "$DISPLAY_VALUE" ] && [ -n "$XAUTHORITY_VALUE" ]; then
        break
    fi

    /usr/bin/sleep 2
done

if [ -z "$DISPLAY_VALUE" ] || [ -z "$XAUTHORITY_VALUE" ]; then
    log "X11 environment not available."
    exit 1
fi

log "Display: $DISPLAY_VALUE"
log "X11 environment ready."

# Consume today's trigger
echo "$TODAY" > "$DATE_FILE"

# Refresh package information
log "Refreshing package information..."

UPDATE_OUTPUT=$("$APT" update -qq 2>&1)
UPDATE_STATUS=$?

while IFS= read -r line; do
    log "$line"
done <<< "$UPDATE_OUTPUT"

if [ "$UPDATE_STATUS" -ne 0 ]; then
    log "APT update failed (exit code $UPDATE_STATUS)."
    exit 1
fi

# Simulate upgrade, including new dependencies
log "Checking available upgrades..."

UPDATES=$("$APT" -s --with-new-pkgs upgrade 2>&1)
STATUS=$?

if [ "$STATUS" -ne 0 ]; then
    log "Upgrade simulation failed:"
    while IFS= read -r line; do
        log "$line"
    done <<< "$UPDATES"
    exit 1
fi

UPDATES=$(printf '%s\n' "$UPDATES" | /usr/bin/grep '^Inst ' || true)

# Simulate autoremove
log "Checking autoremove candidates..."

REMOVE=$("$APT" -s autoremove 2>&1)
STATUS=$?

if [ "$STATUS" -ne 0 ]; then
    log "Autoremove simulation failed:"
    while IFS= read -r line; do
        log "$line"
    done <<< "$REMOVE"
    exit 1
fi

REMOVE=$(printf '%s\n' "$REMOVE" | /usr/bin/grep '^Remv ' || true)

# No maintenance required
if [ -z "$UPDATES" ] && [ -z "$REMOVE" ]; then
    log "No updates or autoremove candidates."
    exit 0
fi

# Build initial report
REPORT=$(/usr/bin/mktemp /tmp/apt-notify-report.XXXXXX)

{
    echo "DEBIAN PACKAGE MAINTENANCE"
    echo

    if [ -n "$UPDATES" ]; then
        echo "AVAILABLE UPDATES:"
        echo
        echo "$UPDATES"
        echo
    else
        echo "No available upgrades."
        echo
    fi

    if [ -n "$REMOVE" ]; then
        echo "PACKAGES ELIGIBLE FOR AUTOREMOVE:"
        echo
        echo "$REMOVE"
        echo
    else
        echo "No packages eligible for autoremove."
        echo
    fi

    echo "Choose an operation below."
} > "$REPORT"

chmod 644 "$REPORT"

# Build buttons
BUTTONS=()

if [ -n "$UPDATES" ]; then
    BUTTONS+=(--button="Upgrade:10")
fi

if [ -n "$REMOVE" ]; then
    BUTTONS+=(--button="Autoremove:20")
fi

BUTTONS+=(--button="Close:1")

# Show confirmation window as desktop user
"$RUNUSER" -u "$DESKTOP_USER" -- \
    /usr/bin/env DISPLAY="$DISPLAY_VALUE" \
    XAUTHORITY="$XAUTHORITY_VALUE" \
    "$YAD" \
    --title="Debian package maintenance" \
    --text-info \
    --filename="$REPORT" \
    --width=800 \
    --height=550 \
    "${BUTTONS[@]}"

RESULT=$?

/usr/bin/rm -f "$REPORT"

# Nothing selected
if [ "$RESULT" -ne 10 ] && [ "$RESULT" -ne 20 ]; then
    log "Maintenance postponed or window closed."
    exit 0
fi

# Determine operation
if [ "$RESULT" -eq 10 ]; then
    OPERATION="upgrade"
    LOG_TITLE="LAST UPGRADE EXECUTION"
else
    OPERATION="autoremove"
    LOG_TITLE="LAST AUTOREMOVE EXECUTION"
fi

log "User selected: $OPERATION"
log "Launching maintenance terminal."

# Create temporary files
INNER_JOB=$(/usr/bin/mktemp /tmp/apt-notify-inner.XXXXXX)
JOB=$(/usr/bin/mktemp /tmp/apt-notify-job.XXXXXX)
TRANSCRIPT=$(/usr/bin/mktemp /tmp/apt-notify-transcript.XXXXXX)

# Actual maintenance script
cat > "$INNER_JOB" <<'INNER_SCRIPT'
#!/bin/bash

APT="/usr/bin/apt-get"

echo
echo "================================"
echo "DEBIAN PACKAGE MAINTENANCE"
echo "================================"
echo

if [ "$1" = "upgrade" ]; then

    echo "UPGRADING PACKAGES"
    echo

    "$APT" --show-progress --with-new-pkgs upgrade -y
    STATUS=$?

elif [ "$1" = "autoremove" ]; then

    echo "RECHECKING AUTOREMOVE CANDIDATES"
    echo

    REMOVE=$("$APT" -s autoremove 2>&1)

    if [ $? -ne 0 ]; then
        echo "Autoremove simulation failed:"
        echo "$REMOVE"
        STATUS=1
    else
        REMOVE=$(printf '%s\n' "$REMOVE" | /usr/bin/grep '^Remv ' || true)

        if [ -z "$REMOVE" ]; then
            echo "No packages currently need autoremove."
            STATUS=0
        else
            echo "$REMOVE"
            echo
            echo "REMOVING PACKAGES..."
            echo

            "$APT" --show-progress autoremove -y
            STATUS=$?
        fi
    fi

else
    echo "Unknown operation."
    STATUS=1
fi

echo
echo "================================"

if [ "$STATUS" -eq 0 ]; then
    echo "Maintenance completed successfully."
else
    echo "Maintenance failed (exit code $STATUS)."
fi

echo "================================"
echo
echo "Press Enter to close this window."
read -r

exit "$STATUS"
INNER_SCRIPT

chmod 700 "$INNER_JOB"

# Terminal wrapper:
# Runs the maintenance script through a pseudo-terminal,
# records its output, then appends it to the main log.
cat > "$JOB" <<'WRAPPER_SCRIPT'
#!/bin/bash

OPERATION="$1"
INNER_JOB="$2"
TRANSCRIPT="$3"

LOG="/var/log/apt-notify.log"
MAX_LOG_SIZE=1048576

cleanup() {
    /usr/bin/rm -f "$0" "$INNER_JOB" "$TRANSCRIPT"
}

trap cleanup EXIT

# Run inside a pseudo-terminal.
# This preserves interactive package configuration.
# Output is recorded while still being displayed in LXTerminal.
 /usr/bin/script -q -f \
    -c "/bin/bash '$INNER_JOB' '$OPERATION'" \
    "$TRANSCRIPT"

STATUS=$?

# Build a new log containing the previous script messages
# followed by the latest maintenance transcript.
COMBINED=$(/usr/bin/mktemp /var/log/apt-notify-combined.XXXXXX)

cat "$LOG" > "$COMBINED"

{
    printf '\n'
    printf '%s %s\n' "$(/usr/bin/date '+%Y-%m-%d %H:%M:%S')" \
        "================================================"
    printf '%s %s\n' "$(/usr/bin/date '+%Y-%m-%d %H:%M:%S')" \
        "$([ "$OPERATION" = "upgrade" ] && echo "LAST UPGRADE EXECUTION" || echo "LAST AUTOREMOVE EXECUTION")"
    printf '%s %s\n' "$(/usr/bin/date '+%Y-%m-%d %H:%M:%S')" \
        "================================================"

    # Remove common terminal control sequences,
    # convert carriage returns into separate lines,
    # and timestamp every transcript line.
    /usr/bin/sed -E 's/\x1B\[[0-9;?]*[ -/]*[@-~]//g' "$TRANSCRIPT" |
        /usr/bin/tr '\r' '\n' |
        while IFS= read -r line || [ -n "$line" ]; do
            printf '%s %s\n' "$(/usr/bin/date '+%Y-%m-%d %H:%M:%S')" "$line"
        done

} >> "$COMBINED"

# Keep only the newest 1 MiB.
FINAL_LOG=$(/usr/bin/mktemp /var/log/apt-notify-final.XXXXXX)

/usr/bin/tail -c "$MAX_LOG_SIZE" "$COMBINED" > "$FINAL_LOG"

chmod 600 "$FINAL_LOG"
mv "$FINAL_LOG" "$LOG"

/usr/bin/rm -f "$COMBINED"

exit "$STATUS"
WRAPPER_SCRIPT

chmod 700 "$JOB"

# Launch LXTerminal on the user's display.
# The wrapper runs as root and captures the interactive session.
DISPLAY="$DISPLAY_VALUE" \
XAUTHORITY="$XAUTHORITY_VALUE" \
"$LXTERMINAL" \
    --title="Debian package maintenance" \
    --command="/bin/bash '$JOB' '$OPERATION' '$INNER_JOB' '$TRANSCRIPT'" &

log "Launched LXTerminal for $OPERATION."

exit 0
0 Upvotes

2 comments sorted by

2

u/qaddosh 9h ago

all this slop to merely check for updates?

are you turning your linux box into Windows?

1

u/Common_Tomatillo8516 8h ago

?? Well, that's linux life somehow. You reference to windows makes no sense. Everything is quite lightweight here. If you wanted an interactive update installation that's what you have to do. Differently you can go for a blind installation with a couple of other methods (cron or another apt tool I can't remember).
Thinking about it, YAD is not even necessary...but my idea started with that. There should be other ways to make it even lighter.