#!/bin/bash

# check for updates and add a little notification to the top offering to install them

if ! command -v pacman; then
    echo "not on an arch system"
    exit
fi

UPDATECOUNT="$(checkupdates | wc -l)"

if ! [ "$UPDATECOUNT" -gt 1 ]; then
    echo "no updates available"
    exit
fi

echo "{heading highlight} Update Notifier
{heading} there are
{heading} $UPDATECOUNT updates available
{heading} ----
{green} update now
{red} later" | instantmenu \
    --no-grab \
    --placeholder 'notification' \
    --lines 20 \
    --x-offset 10000 \
    --y-offset -10 \
    --width auto \
    --border-width 5 >/tmp/updatechoice &

export TMPPID="$!"
echo "tmpid $TMPPID"
COUNTER='.'

while ! grep -q '..................' <<<"$COUNTER":; do
    sleep 1
    echo "waiting for selection $COUNTER"
    COUNTER="$COUNTER."
    if ! kill -0 "$TMPPID" &>/dev/null; then
        echo "menu quit"
        break
    fi
done

if grep -q '..' /tmp/updatechoice; then
    if grep 'update now' /tmp/updatechoice; then
        instantutils open terminal -e bash -c \
            'yay && notify-send "Updates installed successfully" || notify-send -u critical "Updates failed to install"'
    fi
else
    kill "$TMPPID"
fi

rm /tmp/updatechoice
