#!/usr/bin/env python3
"""Authenticated saved Wi-Fi sharing. Secrets and QR images stay in memory."""
import base64
import json
import os
import re
import subprocess
import sys


def field(uid, name, secret=False):
    result = subprocess.run(['/usr/bin/nmcli', '--escape', 'no', '-g', name,
                             *(['--show-secrets'] if secret else []), 'connection', 'show', 'uuid', uid],
                            capture_output=True, text=True, timeout=15, env={**os.environ, 'LC_ALL': 'C'})
    if result.returncode:
        raise ValueError("The saved network couldn't be read. It may have been removed.")
    return result.stdout.removesuffix('\n')


def escape(value):
    return ''.join("\\" + c if c in '\\;,:"' else c for c in value)


def share(uid, reveal=False):
    if not re.fullmatch(r'[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}', uid):
        raise ValueError('Choose a saved Wi-Fi network.')
    if field(uid, 'connection.type') != '802-11-wireless':
        raise ValueError("This saved connection isn't Wi-Fi.")
    ssid = field(uid, '802-11-wireless.ssid')
    kind = field(uid, '802-11-wireless-security.key-mgmt')
    password = ''
    if kind in ('wpa-psk', 'sae'):
        password = field(uid, '802-11-wireless-security.psk', True)
        if not password or password == '--':
            raise ValueError("The password isn't saved in this network profile. Connect and save it first.")
        security = 'WPA' if kind == 'wpa-psk' else 'SAE'
    elif kind in ('', '--', 'none', 'owe'):
        if kind == 'none':
            raise ValueError("QR sharing isn't available for this older Wi-Fi security type.")
        security = 'nopass'
    else:
        raise ValueError("Work or school Wi-Fi needs individual sign-in details and can't be shared this way.")
    hidden = field(uid, '802-11-wireless.hidden') == 'yes'
    payload = f'WIFI:T:{security};S:{escape(ssid)};P:{escape(password)};H:{str(hidden).lower()};;'
    qr = subprocess.run(['/usr/bin/qrencode', '-t', 'PNG', '-s', '8', '-m', '4', '-o', '-'],
                        input=payload.encode(), capture_output=True, timeout=10)
    if qr.returncode or not qr.stdout.startswith(b'\x89PNG\r\n\x1a\n'):
        raise ValueError("The Wi-Fi code couldn't be made. Check Settings > Updates to repair the QR tool.")
    result = {'ok': True, 'ssid': ssid, 'image': 'data:image/png;base64,' + base64.b64encode(qr.stdout).decode(),
              'secured': bool(password)}
    if reveal:
        result['password'] = password
    return result


def main(args):
    # A distinct first argument selects the password-reveal authentication message.
    if len(args) == 2 and args[0] == '--qr-code':
        args = [args[1]]
    elif len(args) == 2 and args[0] == '--reveal-password':
        args = [args[1], args[0]]
    if args in (['-h'], ['--help']):
        print('usage: starchaser-wifi-share UUID [--reveal-password] | --qr-code UUID | --reveal-password UUID'); return 0
    if len(args) not in (1, 2) or len(args) == 2 and args[1] != '--reveal-password':
        print('usage: starchaser-wifi-share UUID [--reveal-password] | --qr-code UUID | --reveal-password UUID', file=sys.stderr); return 2
    if os.geteuid() != 0:
        print(json.dumps({'ok': False, 'errors': 'Use the password prompt in Settings > Network.'})); return 1
    try:
        print(json.dumps(share(args[0], len(args) == 2))); return 0
    except ValueError as error:
        print(json.dumps({'ok': False, 'errors': str(error)})); return 1
    except (OSError, subprocess.TimeoutExpired):
        # Never forward process output: it can include credentials.
        print(json.dumps({'ok': False, 'errors': "Couldn't share this saved Wi-Fi. It must use a saved personal password or be an open network. Work or school sign-ins can't be shared. Check that the QR tool is installed."})); return 1


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