#!/usr/bin/python3 -I
"""Read one local account's faillock deadline. Never authenticate or change its tally."""
import fcntl
import json
import os
import pwd
import re
import stat
import struct
import sys
import time
from pathlib import Path

CONFIG = Path('/etc/security/faillock.conf')
# Linux-PAM's native 64-byte tally ABI: source[52], reserved, status, timestamp.
# https://github.com/linux-pam/linux-pam/blob/master/modules/pam_faillock/faillock.h
RECORD = struct.Struct('=52sHHQ')


def policy(text):
    values = {'deny': 3, 'fail_interval': 900, 'unlock_time': 600, 'dir': '/run/faillock'}
    # Root and administrator exceptions need their own policy; the greeter only offers regular local accounts.
    for raw in text.splitlines():
        line = raw.split('#', 1)[0].strip()
        if not line:
            continue
        name, _, value = line.partition('=')
        name, value = name.strip(), value.strip()
        if name == 'dir':
            if not value.startswith('/'):
                raise ValueError('invalid faillock directory')
            values[name] = value
        elif name in values:
            if not value.isdecimal():
                raise ValueError('unsupported faillock policy')
            values[name] = int(value)
        elif name in ('admin_group', 'root_unlock_time'):
            raise ValueError('administrator faillock policy needs PAM')
    return values


def read_tally(folder, user, uid):
    # faillock --user opens with O_CREAT and can chmod/chown, even without --reset. Open the record ourselves
    # with read-only flags so a fresh greeter cannot create or change authentication state.
    try:
        fd = os.open(Path(folder) / user, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
    except FileNotFoundError:
        return b''
    try:
        info = os.fstat(fd)
        if not stat.S_ISREG(info.st_mode) or info.st_uid != uid:
            raise ValueError('not an account tally')
        fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
        data = os.read(fd, RECORD.size * 1024 + 1)
    finally:
        os.close(fd)
    if len(data) % RECORD.size or len(data) > RECORD.size * 1024:
        raise ValueError('unsupported faillock record size')
    return data


def deadline(data, settings, now):
    valid = []
    for _, reserved, status, stamp in RECORD.iter_unpack(data):
        if reserved or status & ~7:
            raise ValueError('unsupported faillock record')
        if status & 1:
            valid.append(stamp)
    latest = max(valid, default=0)
    count = sum(latest - stamp < settings['fail_interval'] for stamp in valid)
    if not settings['deny'] or count < settings['deny']:
        return {'state': 'ok', 'until': 0}
    if not settings['unlock_time']:
        return {'state': 'paused', 'until': None}
    # PAM accepts a timed pause only once now is strictly beyond latest + unlock_time.
    until = latest + settings['unlock_time'] + 1
    return {'state': 'paused', 'until': until * 1000} if now < until else {'state': 'ok', 'until': 0}


def query(user):
    if not re.fullmatch(r'[a-z_][a-z0-9_-]*\$?', user, re.ASCII) or len(user) > 32:
        raise ValueError('invalid account name')
    account = pwd.getpwnam(user)
    if not 1000 <= account.pw_uid < 60000 or account.pw_shell.rsplit('/', 1)[-1] in ('nologin', 'false'):
        raise ValueError('not a login account')
    try:
        text = CONFIG.read_text()
    except FileNotFoundError:
        text = ''
    settings = policy(text)
    data = read_tally(settings['dir'], user, account.pw_uid)
    return {'user': user, **deadline(data, settings, time.time())}


def main(argv):
    if argv in (['--help'], ['-h']):
        print('Usage: starchaser-greeter-pause ACCOUNT\nRead one login account\'s sign-in pause as JSON. Does not change it.')
        return 0
    if len(argv) != 1 or argv[0].startswith('-'):
        print('Usage: starchaser-greeter-pause ACCOUNT', file=sys.stderr)
        return 2
    try:
        if os.geteuid() != 0:
            raise PermissionError('requires the read-only greeter permission')
        value = query(argv[0])
    except (OSError, ValueError, KeyError, struct.error) as exc:
        print(json.dumps({'user': argv[0], 'state': 'unknown'}))
        print(f'starchaser-greeter-pause: {exc}', file=sys.stderr)
        return 1
    print(json.dumps(value))
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
