#!/bin/bash

#   It is recommended to test the script on a local machine for its purpose and effects.
#   ManageEngine Endpoint Central will not be responsible for any
#   damage/loss to the data/setup based on the behavior of the script.
#   Description: Script to automatically disable the local user accounts that have not logged in for 90 days.
#   Parameters: ExcludeUsersList
#   Ex : "Administrator,Sysadmin"
#   Remarks: The script has to be deployed as Computer Configuration
#   Configuration Type - Computer

if [ -n "$1" ]; then
    ExcludeUsersPattern="$1"
else
    ExcludeUsersPattern=""
fi

CURRENT_DATE=$(date +%s)

while IFS= read -r name; do

    if [[ "$name" == _* ]]; then
        continue
    fi

    UID_VAL=$(dscl . -read /Users/"$name" UniqueID 2>/dev/null | awk '{print $2}')
    if [ -z "$UID_VAL" ] || [ "$UID_VAL" -lt 501 ]; then
        continue
    fi

    # Disabled check - dscl AND pwpolicy
    AUTH=$(dscl . -read /Users/"$name" AuthenticationAuthority 2>/dev/null)
    PWCHECK=$(pwpolicy -u "$name" -getpolicy 2>&1)
    if echo "$AUTH" | grep -q "DisabledUser" || echo "$PWCHECK" | grep -qi "disabled"; then
        continue
    fi
    
    # Exclusion check
    if [ -n "$ExcludeUsersPattern" ]; then
        EXCLUDED=false
        IFS=',' read -ra EXCL_LIST <<< "$ExcludeUsersPattern"
        for excl in "${EXCL_LIST[@]}"; do
            excl=$(echo "$excl" | xargs)
            if [ "$name" = "$excl" ]; then
                EXCLUDED=true
                break
            fi
        done
        if [ "$EXCLUDED" = true ]; then
            continue
        fi
    fi

    PROFILE_PATH="/Users/$name"
    if [ -d "$PROFILE_PATH" ]; then
        LOGIN_FOUND=false
        DAYS_SINCE=0
        LAST_LOGIN_RAW=$(last -1 "$name" 2>/dev/null | head -n 1)
        if ! echo "$LAST_LOGIN_RAW" | grep -qiE "wtmp begins|never logged in"; then
            LOGIN_DATE=$(echo "$LAST_LOGIN_RAW" | grep -oE '[A-Z][a-z]{2} +[0-9]{1,2} +[A-Z][a-z]{2} +[0-9]{2}:[0-9]{2}')
            if [ -n "$LOGIN_DATE" ]; then
                CURRENT_YEAR=$(date +"%Y")
                LOGIN_EPOCH=$(date -j -f "%a %e %b %H:%M %Y" "$LOGIN_DATE $CURRENT_YEAR" "+%s" 2>/dev/null)
                # Year rollback if future date
		if [ -n "$LOGIN_EPOCH" ] && [ "$(( LOGIN_EPOCH - CURRENT_DATE ))" -gt 86400 ]; then
                    PREV_YEAR=$(( CURRENT_YEAR - 1 ))
                    LOGIN_EPOCH=$(date -j -f "%a %e %b %H:%M %Y" "$LOGIN_DATE $PREV_YEAR" "+%s" 2>/dev/null)
                fi
                if [ -n "$LOGIN_EPOCH" ]; then
                    DIFF_SECONDS=$(( CURRENT_DATE - LOGIN_EPOCH ))
                    if [ "$DIFF_SECONDS" -ge 0 ]; then
                        DAYS_SINCE=$(( DIFF_SECONDS / 86400 ))
                        if [ "$DAYS_SINCE" -gt 90 ]; then
			    if pwpolicy -u "$name" -disableuser 2>/dev/null; then
				echo "User '$name' has been disabled. Last activity was $DAYS_SINCE days ago."
			    else
				echo "Error: Failed to disable '$name'."
			    fi
			fi
                        LOGIN_FOUND=true
                    fi
                fi
            fi
        fi
        if [ "$LOGIN_FOUND" = false ]; then
            MTIME_EPOCH=$(stat -f "%m" "$PROFILE_PATH" 2>/dev/null)
            if [ -n "$MTIME_EPOCH" ]; then
                MTIME_DIFF=$(( CURRENT_DATE - MTIME_EPOCH ))
         	MTIME_DAYS=$(( MTIME_DIFF / 86400 ))
		if [ "$MTIME_DAYS" -gt 90 ]; then
		    echo "User '$name': Unable to retrieve last login time. Last profile modification was $MTIME_DAYS days ago. Manual review required."
		fi
            fi
        fi
    fi
done < <(dscl . -list /Users)

echo "Disable Inactive local user Process completed"
