#!/usr/bin/env python3
# summary: Print or show the recovery instructions.
"""The recovery instructions component of the shared emergency sheet.

usage: starchaser recovery sheet text|print|save
Secret fields stay blank here; Drive unlock owns secret creation and renewal.
"""
import argparse
import datetime
import json
import os
import socket
import subprocess
import sys
import unicodedata
from pathlib import Path


def status(command):
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=15)
        data = json.loads(result.stdout)
        return data if result.returncode == 0 and isinstance(data, dict) and data.get('ok', True) else {}
    except (OSError, ValueError, subprocess.TimeoutExpired):
        return {}


def sheet():
    template = Path(__file__).resolve().parents[1] / 'data/recovery-sheet.txt'
    stick = status(['starchaser', 'recovery', 'usb', 'status'])
    backup = status(['starchaser', 'backup', 'status'])
    code = status(['/usr/local/lib/starchaser/starchaser-admin', 'recovery-code-status'])
    security = status(['starchaser', 'security', 'status'])
    disk = security.get('driveUnlock') or {}
    made = stick.get('made') or {}
    def clean(value):
        return ' '.join(''.join(c for c in str(value or '') if c.isspace() or not unicodedata.category(c).startswith('C')).split())[:160]
    try:
        stick_date = datetime.datetime.fromtimestamp(made['time']).strftime('%b %-d, %Y') if made.get('time') else 'Not made yet' if stick else "Couldn't be checked"
    except (ValueError, TypeError, OverflowError):
        stick_date = "Couldn't be checked"
    disk_state = ('Not needed: drive encryption is off' if security.get('encryptionKnown') is True and security.get('encrypted') is False else
                  'You have one' if disk.get('recovery') else 'Not made yet' if disk.get('encrypted') is True and 'recovery' in disk else "Couldn't be checked")
    return template.read_text().format(computer=clean(socket.gethostname()), date=datetime.date.today().strftime('%b %-d, %Y'),
        stick_date=stick_date, stick_version=clean(made.get('version')) or 'Not recorded',
        backup=clean((backup.get('drive') or {}).get('name')) or ('Not set up' if backup else "Couldn't be checked"),
        code_state='You have one' if code.get('has') else 'Not made yet' if code.get('has') is False else "Couldn't be checked", disk_state=disk_state)


def documents_folder():
    try:
        result = subprocess.run(['xdg-user-dir', 'DOCUMENTS'], capture_output=True, text=True, timeout=5)
        if result.returncode == 0 and Path(result.stdout.strip()).is_absolute():
            return Path(result.stdout.strip())
    except (OSError, subprocess.TimeoutExpired):
        pass
    return Path.home() / 'Documents'


def save():
    folder = documents_folder()
    folder.mkdir(parents=True, exist_ok=True)
    path = folder / 'Starchaser recovery sheet.txt'
    # Do not follow a planted symlink, or overwrite a file someone already filled with secrets.
    stem, n = path.stem, 2
    while True:
        try:
            fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
            break
        except FileExistsError:
            path = folder / f'{stem} ({n}).txt'
            n += 1
    with os.fdopen(fd, 'w') as output:
        output.write(sheet())
    return {'ok': True, 'file': str(path), 'folder': str(folder)}


def main():
    parser = argparse.ArgumentParser(prog="starchaser recovery sheet", description=__doc__)
    parser.add_argument('command', choices=['text', 'print', 'save'])
    parser.add_argument('--save', action='store_true', help='save the text sheet in Documents')
    args = parser.parse_args()
    if args.command == 'text' and not args.save:
        print(sheet(), end='')
        return 0
    if args.command == 'save' or args.save:
        print(json.dumps(save()))
        return 0
    result = subprocess.run(['starchaser', 'printers', 'print-text'], input=sheet(), text=True, capture_output=True)
    print(result.stdout, end='')
    return result.returncode


if __name__ == '__main__':
    sys.exit(main())
