#!/bin/sh
#
# Find users whose last login is greater or less than the specified arguments.
# Needs the userinfo utility from http://arbornet.org/~bjk/userinfo/.
#
# Copyright (c) 2003-2004 Ben Kibbey <bjk@arbornet.org>
# Distributed under the terms of the General Public License version 2 or later.
#
# $Log: lastusers.sh,v $
# Revision 2.0  2004-12-05 19:44:23  bjk
# Initial revision
#
# Revision 1.6  2004/11/21 18:48:07  bjk
# Updated to work with userinfo 2.0 (included in the archive).
#
# Revision 1.5  2004/05/01 19:10:37  bjk
# Changed option -b to -l.
#
# Displaying users who have never logged in is off by default. Specify with -n.
#
# Revision 1.4  2003/03/01 19:30:44  bjk
# Changed option -a to -b to specify logins before the arguments.
#
# Added options -s, -m, -r to specify seconds, minutes and hours.
#
# Revision 1.3  2003/03/01 16:14:46  bjk
# Added option -a to specify logins after the arguments.
#
# Revision 1.2  2003/02/26 17:43:22  bjk
# Dont run userinfo on matches. Dump only the username.
#
# Added option -n to suppress users who have never logged in.
#
# Revision 1.1  2003/02/22 20:57:18  bjk
# Initial commit.
#
#
PN="`basename $0`";
MINUTE=60;
HOUR=3600;
DAY=86400;
WEEK=604800;
YEAR=31449600;
CMD="awk -F: '{print \$1}' < /etc/passwd | ui -O passwd.so -l -- -O login.so -lt --";

usage () {
    cat <<EOF 1>&2
Find users whose last login is greater or less than the specified arguments.
Usage: $PN [-hnl] [-s seconds] [-m minutes] [-r hours] [-d days]
           [-w weeks] [-y years]
    -s  Logins seconds old.
    -m  Logins minutes old.
    -r  Logins hours old.
    -d  Logins days old.
    -w  Logins weeks old.
    -y  Logins years old.
    -l  List users whose last login is at least as old as the arguments.
    -n  Also show users who have never logged in.
    -h  This help text.
EOF
    exit 1;
}

while getopts "d:w:hr:m:nls:y:" opt; do
    case $opt in
        l) BEFORE=1;;
	n) NOLOGIN=1;;
	s) tmp=`expr $OPTARG`;;
	d) tmp=`expr $OPTARG \* $DAY`;;
	w) tmp=`expr $OPTARG \* $WEEK`;;
	r) tmp=`expr $OPTARG \* $HOUR`;;
	m) tmp=`expr $OPTARG \* $MINUTE`;;
	y) tmp=`expr $OPTARG \* $YEAR`;;
	h) usage;;
	\?) usage;;
	--) break;;
    esac;

    if [ $WHEN ]; then
	WHEN=`expr $WHEN + $tmp`;
    else
	WHEN=$tmp;
    fi;
done;

if [ ! $WHEN ]; then
    usage;
fi;

shift $(($OPTIND - 1));

NOW=`date +%s`;
OLDIFS=$IFS;

eval $CMD | while read line; do
    IFS=:;
    set $line;
    user="$1";
    sec="$2";

    if [ x"$sec" = x- -o x"$sec" = x\! ]; then
	if [ $NOLOGIN ]; then
	    echo "$user";
	fi;

	continue;
    fi;

    if [ $BEFORE ]; then
	if [ `expr $NOW - $sec` -gt $WHEN ]; then
	    echo "$user";
	fi;
    else
	if [ `expr $NOW - $sec` -lt $WHEN ]; then
	    echo "$user";
	fi;
    fi;
done;

IFS=$OLDIFS;
exit 0;


syntax highlighted by Code2HTML, v. 0.9.1