#!/usr/bin/python3
"""Add one high-priority zram swap device on low-memory Compact Desktop machines."""
import errno
import fcntl
from pathlib import Path
import re
import subprocess
import sys
import time

GIB = 1024 ** 3


def policy(meminfo, swaps):
    found = re.search(r'^MemTotal:\s+([0-9]+)\s+kB$', meminfo, re.M)
    if not found:
        raise ValueError("could not read total usable memory")
    ram = int(found[1]) * 1024
    if ram < 4096 or ram > 4 * GIB:
        return None
    priorities = [-1]
    for line in swaps.splitlines()[1:]:
        fields = line.split()
        if not fields:
            continue
        if re.fullmatch('/dev/zram[0-9]+', fields[0]):
            return None
        priorities.append(int(fields[-1]))
    highest = max(priorities)
    if highest >= 32767:  # Preserve the administrator's maximum-priority choice.
        return None
    return (min(ram // 2, GIB) // 4096 * 4096, max(100, highest + 1))


def write_while_device_settles(attribute, value):
    # udev may briefly hold a new block device open during its initial probe.
    for attempt in range(12):
        try:
            attribute.write_text(value)
            return
        except OSError as exc:
            if exc.errno != errno.EBUSY or attempt == 11:
                raise
            time.sleep(0.1)


def start(proc=Path('/proc'), sysfs=Path('/sys'), dev=Path('/dev'), run=subprocess.run):
    config = policy((proc / 'meminfo').read_text(), (proc / 'swaps').read_text())
    if not config:
        return
    for existing in (sysfs / 'block').glob('zram[0-9]*'):
        if int((existing / 'disksize').read_text()) > 0:
            return
    control = sysfs / 'class/zram-control'
    if not (control / 'hot_add').exists():
        run(['/usr/sbin/modprobe', 'zram'], check=True)
    # hot_add reserves a NEW device, including when an unused admin device exists.
    index = (control / 'hot_add').read_text().strip()
    if not re.fullmatch(r'[0-9]+', index):
        raise ValueError('invalid zram device number')
    device = dev / ('zram' + index)
    size, priority = config
    try:
        for _ in range(100):
            if device.exists():
                break
            time.sleep(0.05)
        else:
            raise OSError('timed out waiting for the new device node')
        # hot_add gives us an uninitialized device. zramctl --size on an explicit
        # device resets it first, which races udev's open file descriptor.
        write_while_device_settles(sysfs / 'block' / device.name / 'disksize', str(size))
        run(['/usr/bin/udevadm', 'settle', '--timeout=2'], check=False)
        run(['/usr/sbin/mkswap', '--label', 'compact-zram', str(device)], check=True)
        run(['/usr/sbin/swapon', '--priority', str(priority), str(device)], check=True)
    except (OSError, subprocess.CalledProcessError):
        # The kernel refuses to remove an in-use device. Touch only the one we obtained.
        try:
            write_while_device_settles(control / 'hot_remove', index)
        except OSError as exc:
            print(f'Could not release unused {device}: {exc}', file=sys.stderr)
        raise
    print(f'Enabled {device} with {size // 1048576} MiB logical swap at priority {priority}.')


def main():
    # A lock also serializes manual retries on a running installed system.
    with Path('/run/compact-low-memory.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        start()


if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, subprocess.CalledProcessError) as err:
        sys.exit(f'Optional compressed swap could not start: {err}')
