#!/usr/bin/python3
"""Consume one fixed SIG power request; run only from the root systemd unit."""
import json
import fcntl
import os
from pathlib import Path
import pwd
import stat
import subprocess
import sys
import tempfile
import time

REQUEST = Path('/var/lib/sig/power-request.json')
SPOOL = Path('/var/lib/sig-power')
MAINTENANCE = Path('/run/sig-maintenance')
LOCK = MAINTENANCE / 'lock'
SCHEDULED = MAINTENANCE / 'power-scheduled'


def validate_request(fd, uid, now):
    info = os.fstat(fd)
    if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_uid != uid or info.st_nlink != 1:
        raise ValueError('request must be a private regular file owned by sig')
    if info.st_size > 256:
        raise ValueError('request exceeds 256 bytes')
    data = os.read(fd, 257)
    if len(data) > 256:
        raise ValueError('request exceeds 256 bytes')
    def unique_fields(pairs):
        result = {}
        for key, value in pairs:
            if key in result:
                raise ValueError('duplicate request field')
            result[key] = value
        return result
    try:
        request = json.loads(data, object_pairs_hook=unique_fields)
    except (UnicodeError, json.JSONDecodeError):
        raise ValueError('request is not valid JSON') from None
    if not isinstance(request, dict) or set(request) != {'action', 'requestedAt'}:
        raise ValueError('request must contain only action and requestedAt')
    if request['action'] not in ('restart', 'shutdown'):
        raise ValueError('unsupported power action')
    timestamp = request['requestedAt']
    if type(timestamp) is not int or not 0 <= now - timestamp <= 60:
        raise ValueError('request timestamp is stale or in the future')
    return request['action']


def claim_request():
    # Claim into a root-only directory on the same /var/lib filesystem. This
    # avoids unlink races in the API-owned inbox and never follows a symlink.
    spool_info = SPOOL.lstat()
    if not stat.S_ISDIR(spool_info.st_mode) or spool_info.st_uid != 0 or stat.S_IMODE(spool_info.st_mode) != 0o700:
        raise ValueError('power spool must be a root-owned private directory')
    claim_dir = Path(tempfile.mkdtemp(prefix='claim-', dir=str(SPOOL)))
    claim = claim_dir / 'request.json'
    try:
        os.rename(REQUEST, claim)
        fd = os.open(claim, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
        try:
            action = validate_request(fd, pwd.getpwnam('sig').pw_uid, int(time.time()))
        finally:
            os.close(fd)
    finally:
        # Only the claimed directory entry is removed, including invalid input.
        # A malformed directory is left for operator inspection; the inbox is
        # still empty so PathExists does not repeatedly trigger it.
        if claim.is_symlink() or (claim.exists() and not claim.is_dir()):
            claim.unlink()
        if not claim.exists():
            claim_dir.rmdir()
    return action


def dispatch(action):
    command = 'reboot' if action == 'restart' else 'poweroff'
    # Persist until reboot so an update cannot start after asynchronous power
    # dispatch releases the maintenance lock.
    fd = os.open(SCHEDULED, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
    os.close(fd)
    try:
        subprocess.run(['/usr/bin/systemctl', '--no-block', command],
                       check=True, capture_output=True, timeout=30)
    except (OSError, subprocess.SubprocessError):
        SCHEDULED.unlink()
        raise
    print('sig-power: scheduled ' + action, flush=True)


def execute_request():
    info = MAINTENANCE.lstat()
    if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or stat.S_IMODE(info.st_mode) != 0o700:
        raise ValueError('maintenance directory must be root private')
    for ancestor in MAINTENANCE.parents:
        if ancestor.is_symlink():
            raise ValueError('redirected maintenance directory')
    fd = os.open(LOCK, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
    try:
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            # Consume/reject without power dispatch. Leaving PathExists set
            # would repeatedly restart this helper during a long DNF transaction.
            claim_request()
            raise ValueError('maintenance operation active; power request rejected') from None
        dispatch(claim_request())
    finally:
        os.close(fd)


def main():
    if os.geteuid() != 0:
        print('sig-power: must run as root through sig-power.service', file=sys.stderr)
        return 1
    try:
        execute_request()
    except FileNotFoundError:
        print('sig-power: request missing; inspect the inbox and sig-power.service journal', file=sys.stderr)
        return 1
    except (ValueError, OSError, KeyError, subprocess.SubprocessError) as error:
        detail = str(error) if isinstance(error, ValueError) else type(error).__name__
        print('sig-power: rejected or failed request (' + detail +
              '); inspect ownership/mode, request age, and systemctl status', file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    sys.exit(main())
