#!/usr/bin/env python3
# summary: Explain when startup needed the drive recovery key.
"""Notify after a start that needed the drive's recovery key.

Usage: starchaser drive unlock notify
"""
import json
import os
import subprocess
import sys
from pathlib import Path


def notify(state=Path('/run/starchaser-drive-unlock.json'), runtime=None, runner=subprocess.run):
    try:
        data = json.loads(state.read_text())
    except (OSError, ValueError):
        return
    if not data.get('recoveryBoot') and not data.get('firmwareRelink'):
        return
    folder = Path(runtime or os.environ.get('XDG_RUNTIME_DIR', '/run/user/' + str(os.getuid())))
    mark = folder / 'starchaser-drive-unlock-notified'
    try:
        fd = os.open(mark, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        os.close(fd)
    except FileExistsError:
        return
    result = runner([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], 'starchaser', 'notify', '-a', 'Starchaser', '-u', 'critical', '-w',
                     '-A', 'link=Link this computer again', 'Firmware was updated. Link this computer again?' if data.get('firmwareRelink') else 'Your drive needed its recovery key. Link this computer again?',
                     'Open Settings > Security > Drive unlock to repair the link after your account password. PIN protection and your recovery key are kept.'], capture_output=True, text=True)
    if result.returncode:
        mark.unlink(missing_ok=True)
    elif result.stdout.strip() == 'link':
        runner(['starchaser', 'settings', 'security'], check=False)


def main(argv):
    if argv in (['--help'], ['-h']):
        print(__doc__)
        return 0
    if argv == ['notify']:
        notify()
        return 0
    print(__doc__, file=sys.stderr)
    return 2


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