#!/usr/bin/env python3
# summary: Preview, save, or print a private emergency sheet.
"""Make a private emergency sheet from JSON on standard input.

Usage: starchaser emergency sheet devices | printers | preview | save MOUNT | print [PRINTER]
       starchaser emergency sheet --help

preview writes a PDF and QR image to a private folder in your RAM session directory.
save writes to a different mounted USB stick. print sends the PDF to the default printer.
The QR code contains the same private codes as the printed sheet. Keep it somewhere safe.
"""
import io
import json
import os
import re
import subprocess
import sys
import tempfile
from datetime import date
from pathlib import Path


def validate(data):
    if not isinstance(data, dict) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9-]{0,62}', data.get('hostname', '')):
        raise ValueError('Enter the computer name for the emergency sheet.')
    for name, pattern in (('key', r'[a-z]{8}(-[a-z]{8}){7}'), ('code', r'[A-Z2-9]{4}(-[A-Z2-9]{4}){3}')):
        value = data.get(name, '')
        if not isinstance(value, str) or value and not re.fullmatch(pattern, value):
            raise ValueError("The emergency codes couldn't be read. Keep the codes shown on screen.")
    if not data.get('key') and not data.get('code'):
        raise ValueError('There are no emergency codes to save.')
    return data


def qr_payload(data):
    validate(data)
    return json.dumps({'format': 'starchaser-emergency-1', 'computer': data['hostname'],
                       'driveKey': data.get('key', ''), 'passwordCode': data.get('code', '')}, separators=(',', ':'))


def render(data):
    validate(data)
    from reportlab.graphics import renderPDF, renderSVG
    from reportlab.graphics.barcode.qr import QrCodeWidget
    from reportlab.graphics.shapes import Drawing, Rect
    from reportlab.lib.colors import white
    from reportlab.lib.pagesizes import letter
    from reportlab.pdfgen import canvas

    qr = QrCodeWidget(qr_payload(data), barLevel='M')
    x0, y0, x1, y1 = qr.getBounds()
    size = 216
    drawing = Drawing(size, size, transform=[size / (x1 - x0), 0, 0, size / (y1 - y0), 0, 0])
    drawing.add(Rect(x0, y0, x1 - x0, y1 - y0, fillColor=white, strokeColor=None))
    drawing.add(qr)
    stream = io.BytesIO()
    pdf = canvas.Canvas(stream, pagesize=letter)
    pdf.setTitle('Starchaser emergency sheet')
    pdf.setAuthor('Starchaser')
    pdf.setFont('Helvetica-Bold', 24)
    pdf.drawString(48, 730, 'Your emergency sheet')
    pdf.setFont('Helvetica', 12)
    pdf.drawString(48, 709, 'Starchaser Linux')
    pdf.drawString(48, 692, 'Made on ' + date.today().strftime('%B %-d, %Y'))
    pdf.drawString(48, 675, 'Computer: ' + data['hostname'])
    pdf.setFont('Helvetica-Bold', 12)
    pdf.drawString(48, 657, 'Recovery key')
    pdf.setFont('Courier', 13)
    groups = data.get('key', '').split('-')
    if data.get('key'):
        pdf.drawString(48, 635, '-'.join(groups[:4]) + '-')
        pdf.drawString(48, 615, '-'.join(groups[4:]))
    else:
        pdf.drawString(48, 635, 'No recovery key on this sheet')
    pdf.setFont('Helvetica', 11)
    pdf.drawString(48, 588, 'Type this when the startup screen asks,')
    pdf.drawString(48, 572, 'if the security chip stops working or you forget your startup PIN.')
    pdf.setFont('Helvetica-Bold', 12)
    pdf.drawString(48, 550, 'Password recovery code')
    pdf.setFont('Courier', 16)
    pdf.drawString(48, 525, data.get('code') or 'Not renewed on this sheet')
    pdf.setFont('Helvetica', 11)
    pdf.drawString(48, 499, 'Choose "Can\'t log in?" or "Can\'t unlock?" to set a new password.')
    pdf.drawString(48, 482, 'This code works once. It does not replace the recovery key.')
    renderPDF.draw(drawing, pdf, 198, 236)
    for y, text in ((211, 'The QR code contains the computer name and both codes above.'),
                    (193, 'Scan it only with a device you trust. Do not upload it to a website.'),
                    (151, 'Keep this sheet away from this computer, in a safe place.'),
                    (133, 'Anyone with these codes may be able to read your files.'),
                    (103, 'Renew it in Settings > Security > Disk key and unlocking.'),
                    (85, 'A new recovery key or password code makes its old code stop working.')):
        pdf.drawCentredString(306, y, text)
    pdf.showPage()
    pdf.save()
    return stream.getvalue(), renderSVG.drawToString(drawing).encode()


def usb_mounts(runner=subprocess.run):
    result = runner(['lsblk', '-J', '-p', '-o', 'PATH,TYPE,TRAN,RM,LABEL,FSTYPE,MAJ:MIN,MOUNTPOINTS'], capture_output=True, text=True, check=True)
    def nodes(node):
        return [node] + [n for child in node.get('children', []) for n in nodes(child)]
    found = []
    for disk in json.loads(result.stdout).get('blockdevices', []):
        parts = nodes(disk)
        mounts = [m for n in parts for m in n.get('mountpoints') or [] if m]
        # Never save to the running system or the installer, even if it has another mounted partition.
        if disk.get('tran') != 'usb' or any(n.get('label') == 'STARCHASER' for n in parts) or any(m in ('/', '/home', '/boot', '/efi') or m.startswith('/run/archiso') for m in mounts):
            continue
        for node in parts:
            for mount in node.get('mountpoints') or []:
                if mount and mount not in ('[SWAP]',):
                    found.append({'path': mount, 'device': node.get('path'), 'devnum': node.get('maj:min'),
                                  'label': (node.get('label') or 'USB stick') + ' - ' + mount})
            if not any(node.get('mountpoints') or []) and node.get('fstype') in ('vfat', 'exfat', 'ext4', 'btrfs', 'ntfs', 'ntfs3'):
                found.append({'path': node['path'], 'device': node['path'], 'devnum': node.get('maj:min'),
                              'label': (node.get('label') or 'USB stick') + ' - ' + node['path']})
    return found


def save_usb(mount, pdf, computer):
    if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9-]{0,62}', computer):
        raise ValueError('Enter the computer name for the emergency sheet.')
    mount = Path(mount)
    chosen = next((d for d in usb_mounts() if d['path'] == str(mount)), None)
    if chosen is None:
        raise ValueError("Choose another USB stick. The installer stick and internal drives can't be used.")
    if str(mount).startswith('/dev/'):
        subprocess.run(['udisksctl', 'mount', '--block-device', str(mount), '--no-user-interaction'],
                       check=True, capture_output=True, text=True, timeout=30)
        chosen = next((d for d in usb_mounts() if d.get('device') == str(mount) and not d['path'].startswith('/dev/')), None)
        if chosen is None:
            raise ValueError("The USB stick couldn't be opened. Open it in Files and try again.")
        mount = Path(chosen['path'])
    # Re-check the actual mount and refuse links and overwrites, including a stick with a hostile filename.
    folder = os.open(mount, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
    stem = f'Starchaser-emergency-sheet-{computer}-{date.today().isoformat()}'
    try:
        actual = os.fstat(folder).st_dev
        if chosen.get('devnum') and chosen['devnum'] != f'{os.major(actual)}:{os.minor(actual)}':
            raise ValueError('The USB stick was removed or changed. Choose it again.')
        number = 1
        while True:
            name = stem + (f'-{number}' if number > 1 else '') + '.pdf'
            try:
                fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=folder)
                break
            except FileExistsError:
                number += 1
        with os.fdopen(fd, 'wb') as stream:
            stream.write(pdf)
            stream.flush()
            os.fsync(stream.fileno())
        os.fsync(folder)
    finally:
        os.close(folder)
    return str(mount / name)


def printer_names(runner=subprocess.run):
    if Path('/run/archiso').is_dir():
        # The live image has no saved printer setup. Start discovery only after the person chooses Print.
        started = runner(['sudo', '-n', 'systemctl', 'start', 'cups.socket', 'avahi-daemon.service', 'ipp-usb.service'],
                         capture_output=True, text=True, timeout=30)
        if started.returncode:
            raise ValueError("Printing couldn't start. Save the sheet to another USB stick instead.")
    result = runner(['lpstat', '-e'], capture_output=True, text=True, timeout=30)
    if result.returncode:
        raise ValueError("The printers couldn't be checked. Save the sheet to another USB stick instead.")
    return sorted({name for name in result.stdout.splitlines() if re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_.-]{0,126}', name)})


def print_pdf(pdf, runner=subprocess.run, printer=None):
    if printer is not None and printer not in printer_names(runner):
        raise ValueError('That printer is no longer available. Choose Print again.')
    destination = ['-d', printer] if printer else []
    result = runner(['lp', *destination, '-t', 'Starchaser emergency sheet', '-o', 'job-sheets=none', '-'], input=pdf, capture_output=True, timeout=30)
    if result.returncode:
        raise ValueError("The printer didn't accept the sheet. Check Settings > Printers.")


def main(argv):
    if argv in (['--help'], ['-h']):
        print(__doc__)
        return 0
    if argv == ['devices']:
        print(json.dumps({'ok': True, 'devices': usb_mounts()}))
        return 0
    if argv == ['printers']:
        print(json.dumps({'ok': True, 'printers': printer_names()}))
        return 0
    if argv not in (['preview'], ['print']) and not (len(argv) == 2 and argv[0] in ('save', 'print')):
        print(__doc__, file=sys.stderr)
        return 2
    data = json.loads(sys.stdin.read(16385))
    pdf, svg = render(data)
    result = {'ok': True}
    if argv[0] == 'preview':
        # XDG_RUNTIME_DIR is tmpfs on an installed system; no private codes go to the home folder.
        runtime = Path(os.environ.get('XDG_RUNTIME_DIR', '/run'))
        folder = Path(tempfile.mkdtemp(prefix='starchaser-emergency-', dir=runtime))
        for name, content in (('sheet.pdf', pdf), ('qr.svg', svg)):
            file = folder / name
            with file.open('wb') as stream:
                os.fchmod(stream.fileno(), 0o600)
                stream.write(content)
        result.update(pdf=str(folder / 'sheet.pdf'), qr=str(folder / 'qr.svg'))
    elif argv[0] == 'save':
        result['saved'] = save_usb(argv[1], pdf, data['hostname'])
    else:
        print_pdf(pdf, printer=argv[1] if len(argv) == 2 else None)
        result['queued'] = True
    print(json.dumps(result))
    return 0


def run(argv):
    try:
        return main(argv)
    except (ValueError, OSError, subprocess.SubprocessError, ImportError):
        action = argv[0] if argv else ''
        message = ("The sheet couldn't be saved to that USB stick. Check that it has room and isn't read-only."
                   if action == 'save' else "The printer didn't accept the sheet. Check Settings > Printers."
                   if action == 'print' else "The emergency sheet couldn't be prepared. Keep the codes on screen.")
        print(json.dumps({'ok': False, 'errors': message}))
        return 1


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