#!/bin/bash
set -e

for p in trizen pacaur yaourt pacman; do
    if $p --version &>/dev/null; then
        PAC="$p"
        break;
    fi
done

if [ -z "$PAC" ]; then
    >&2 echo "Error: No Arch package manager found?"
fi

if [ "$BLOCK_BUTTON" == 1 ]; then
    nohup i3-sensible-terminal -r i3blocks-update-term -e "sh -c '$PAC -Syu || exec zsh; pkill -RTMIN+5 i3blocks'" &>/dev/null &
    disown
fi

if [ $p = "pacman" ]; then
    exec 3< <(checkupdates)
else
    exec 3< <({ checkupdates & cower -u & })
fi

count="$(wc -l <&3)"

if [ -n "$count" -a "$count" -gt 0 ]; then
    echo $count
    echo $count
fi
