#!/usr/bin/env python3

# time_tracker.py
# 2023-02-03
# by Gernot WALZL

# This script prints a list of the last login and logout events in CSV format.

import os
import re
import subprocess
from datetime import datetime, timedelta


def parse_duration(duration):
    days = 0
    if "+" in duration:
        str_days, duration = duration.split("+")
        days = int(str_days)
    str_hours, str_minutes = duration.split(":")
    hours = int(str_hours)
    minutes = int(str_minutes)
    return timedelta(days=days, hours=hours, minutes=minutes)


def read_last_sessions(username, tty):
    results = []
    proc = subprocess.Popen(
        ["last", "-R", "--time-format=iso", username],
        stdout=subprocess.PIPE)
    for line in proc.stdout.readlines():
        result = re.search(
            r"(\S+)\s+(\S+)\s+(\S+) - (\S+)\s+\((\S+)\)",
            line.decode('utf-8'))
        if result:
            if result.group(2) == tty:
                dt_login = datetime.fromisoformat(result.group(3))
                duration = parse_duration(result.group(5))
                try:
                    dt_logout = datetime.fromisoformat(result.group(4))
                except ValueError:
                    dt_logout = dt_login + duration
                results.append((dt_login, dt_logout, duration))
    return results


def format_date(dt):
    return dt.strftime("%Y-%m-%d")


def format_time(dt):
    return dt.strftime("%H:%M")


def format_delta(delta):
    seconds = delta.total_seconds()
    hours, remainder = divmod(seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    return "{:02d}:{:02d}".format(int(hours), int(minutes))


if __name__ == "__main__":
    sessions = read_last_sessions(os.getenv("USER"), "tty7")
    for (login, logout, duration) in reversed(sessions):
        print("{},{},{},,login".format(
            int(login.timestamp()),
            format_date(login),
            format_time(login)))
        print("{},{},,{},logout".format(
            int(logout.timestamp()),
            format_date(logout),
            format_time(logout)))