#!/bin/bash

# Scripts to list last recorded login of users
# Copyright (C) 2026 FUSS Project <info@fuss.bz.it>
# Authors: Simone Piccardi <piccardi@truelite.it>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

#
# Usage:
#  ./lastlogs.sh
# 

usage () {
    echo "Usage: ./lastlogs"
}

# no arguments
if [ "$#" -ne 0 ]; then
    usage
    exit 1
fi

# check if run by root
if [ `id -u` != 0 ]; then 
    echo "You must be root to use this script"
    exit 1
fi

#
# exclude following users from search:
# give a space separated list
#
EXCLUDED_USERS="admin nobody"

#
# Users that aren't seen in ~/.lastlogin should be looked for in the freeradius
# logs
#
NEVER_LOGGED=()

#
# searching in ~/.lastlogin, where last GUI login is logged
# 
for i in $(getent -s ldap passwd|tr -d " "); do
    USR=$(echo $i|cut -d: -f1)
    if ! echo $EXCLUDED_USERS | egrep "\b$USR\b" > /dev/null; then
	HOM=$(echo $i|cut -d: -f6)
	if [ -s $HOM/.lastlogin ]; then
	    echo "User $USR last login $(awk '{print $3}' $HOM/.lastlogin)"
	else
            NEVER_LOGGED+=("$USR")
	    #echo "User $USR never logged in"
	fi
    fi
done

for USR in ${NEVER_LOGGED[*]}; do
    LATEST=$(zgrep -h $USR /var/log/freeradius/radius.log* | grep "Login OK" | head -n 1 | cut -c 1-24)
    if [ "x$LATEST" == "x" ]
    then
	echo "User $USR never logged in"
    else
        echo "User $USR last login (wifi) $LATEST"
    fi
done
