bin/has-logged-in-since.sh

83 lines
1.9 KiB
Bash
Executable File

#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail
shopt -s globstar nullglob
function show-help ()
{
local -ir retcode="${1:-1}"
cat >&2 <<EOF
usage: $(basename "$0") [OPTION...] DAYS
Report whether the invoking user has logged in within the past DAYS
days, in the opinion of last(1). DAYS is a positive integer. Exit
status is 0 if the answer is yes, or another value if the answer is no
or an error occurred.
OPTIONS
-v Verbosity. Repeat for more verbosity.
-h This help.
Examples
\$ $(basename "$0") 30
\$ $(basename "$0") -vv 90
EOF
exit "$retcode"
}
#----------------------------------------------------------------------------
declare -i VERBOSITY=0
while getopts ":hv" opt
do
case $opt in
v ) ((++VERBOSITY)) ;;
* ) show-help 0;;
esac
done
shift $((OPTIND - 1))
#----------------------------------------------------------------------------
function squawk ()
{
local -i NVOL=$1; shift
if ((0 == NVOL)); then
echo >&2 "$(basename "$0") $(date +'%T %Z')" "$@"
exit 1
elif ((NVOL <= VERBOSITY)); then
echo "$(basename "$0") $(date +'%T %Z')" "$@"
fi
return 0
}
#----------------------------------------------------------------------------
function login-count ()
{
local -ir days="$1"
last --since -${days}days "$LOGNAME" | head --lines=-2 | wc -l
return 0
}
#----------------------------------------------------------------------------
((1 == $#)) || show-help 99
if [[ -z $1 || $1 = *[!0123456789]* || (($1 < 1)) ]]; then
squawk 0 "DAYS must be a positive integer."
fi
declare -ir days_ago="$1"
squawk 1 "$(date --iso) started."
declare -i main_return=1
# shellcheck disable=SC2155
declare -ir login_count="$(login-count "$days_ago")"
squawk 1 "found $login_count logins by $LOGNAME since $days_ago days ago."
if ((0 < login_count))
then
main_return=0
fi
squawk 1 "done."
exit $main_return