#!/usr/bin/python3
# SPDX-License-Identifier: Apache-2.0
"""Refuse package mutation while a disk or unresolved session is owned."""
import fcntl
import os
from pathlib import Path
import select
import signal
import sys
import time
COORDINATOR = '/usr/libexec/hushdisk/hushdisk-session'


def coordinators():
    """Running session coordinators, including ones whose binary was replaced."""
    found = []
    for process in Path('/proc').glob('[0-9]*'):
        try:
            if os.readlink(process/'exe').removesuffix(' (deleted)') == COORDINATOR:
                found.append(int(process.name))
        except OSError:
            continue
    return found


def stop_coordinators():
    """Removal deletes the coordinator. begin already refused while any disk
    session exists and set the update marker the broker honors, so the
    remaining coordinators are idle; SIGTERM saves their state and exits."""
    handles = []
    for pid in coordinators():
        try:
            handle = os.pidfd_open(pid)
        except ProcessLookupError:
            continue
        try:
            same = os.readlink(f'/proc/{pid}/exe').removesuffix(' (deleted)') == COORDINATOR
        except OSError:
            same = False
        if same:
            try:
                signal.pidfd_send_signal(handle, signal.SIGTERM)
                handles.append(handle)
                continue
            except ProcessLookupError:
                pass
        os.close(handle)
    deadline = time.monotonic() + 15
    while handles and time.monotonic() < deadline:
        ready, _, _ = select.select(handles, [], [], max(0, deadline - time.monotonic()))
        for handle in ready:
            handles.remove(handle)
            os.close(handle)
    if handles:
        sys.exit('A HushDisk session service did not stop. Sign out of the other accounts and retry the removal.')
root = Path('/run/hushdisk')
root.mkdir(mode=0o700, parents=True, exist_ok=True)
with (root/'update.lock').open('a') as lock:
    fcntl.flock(lock, fcntl.LOCK_EX)
    if sys.argv[1] == 'begin':
        records = Path('/var/lib/hushdisk/sessions')
        if records.exists() and any(records.glob('*.json')):
            sys.exit('HushDisk has active or unresolved disk sessions. Run "hushdisk sessions", unmount what is mounted, '
                     'and retire sessions left by a crash with "hushdisk recover-session ID --acknowledge-unclean" '
                     '(Retire Inactive Session in the app), then try again.')
        for process in Path('/proc').glob('[0-9]*'):
            try:
                executable = os.readlink(process/'exe').removesuffix(' (deleted)')
            except FileNotFoundError:
                continue
            except PermissionError:
                try:
                    name = (process/'comm').read_text().strip()
                except FileNotFoundError:
                    continue
                if name in ('hushdisk', 'hushdisk-engine'):
                    sys.exit('Cannot inspect a running HushDisk process. Close HushDisk and command-line operations before updating.')
                continue
            if Path(executable).name in ('hushdisk', 'hushdisk-engine'):
                sys.exit('Finish HushDisk operations and quit the app in every account before updating or removing it.')
        marker = root/'updating'
        fd = os.open(marker, os.O_CREAT | os.O_WRONLY | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
        os.write(fd, b'Package transaction in progress\n'); os.fsync(fd); os.close(fd)
    elif sys.argv[1] == 'stop-sessions':
        stop_coordinators()
    elif sys.argv[1] == 'end':
        (root/'updating').unlink(missing_ok=True)
    else:
        sys.exit('Unknown package guard action')
