#!/usr/bin/python3

# Copyright 2016 Nick Novitski

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script will exit with status zero if there are any current sessions, or
# if a session has been removed in the last hour. Otherwise it exits with
# status 1.

from systemd import login, journal
import argparse
import time
import datetime

def minutes_ago(m):
    return datetime.datetime.fromtimestamp(time.time() - 60*m)

def journal():
    j = journal.Reader()
    j.this_boot()
    j.add_match(SYSLOG_IDENTIFIER='systemd-logind')
    return j

def is_a_logout(event):
    return event['MESSAGE'].startswith('Removed session')

def happened_since(event, t):
    return event['_SOURCE_REALTIME_TIMESTAMP'] > t

def logout_since(event, minutes):
    return is_a_logout(event) and happened_since(event, minutes_ago(minutes))

def logouts(minutes):
    return [e for e in journal() if logout_since(e, minutes)]

def sessions():
    return login.sessions()

def parser():
    p = argparse.ArgumentParser(description='Determine if the system is in-use by a human.')
    p.add_argument('-m', '--minutes', type=int, default=60, help='Number of minutes back to look for sessions.')
    return p

args = parser().parse_args()

if (len(sessions()) > 0):
    exit(0)
else:
    if(len(logouts(args.minutes)) > 0):
        exit(0)
    else: 
        exit(1)
