#!/usr/bin/env python3
# summary: Read the Recovery Safety net checklist.
"""Read the Recovery Safety net checklist without collecting any secrets.

usage: starchaser safety [status]
"""
import argparse
import datetime
import json
import subprocess
from pathlib import Path


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


def checklist(snapshots, stick, code, disk, backup):
    snapshots_ready = bool(snapshots.get('configured') and snapshots.get('allowed') and snapshots.get('autoBeforeChanges'))
    made = (stick.get('made') or {}).get('time')
    backup_ready = bool(backup.get('last') and not backup.get('error') and not backup.get('overdueDays'))
    rows = [
        {'title': 'Snapshots', 'ready': snapshots_ready,
         'state': 'On. One is taken before every software change.' if snapshots_ready else 'Snapshots are off.',
         'action': 'Turn on snapshots', 'section': 'recovery', 'find': '@snapshots'},
        {'title': 'Recovery USB stick', 'ready': bool(made),
         'state': 'Made ' + datetime.datetime.fromtimestamp(made).strftime('%b %-d, %Y') + '.' if made else 'Not made yet.',
         'action': 'Make a recovery USB stick', 'secondary': 'Make a new one' if made else '', 'section': 'recovery', 'find': '@usbprepare'},
        {'title': 'Password recovery code', 'ready': bool(code.get('has')), 'state': 'You have one.' if code.get('has') else 'Not made yet.',
         # One press makes the code: Users' @make-recovery-code target starts it and shows it (fable-final N13).
         # "Replace it…" only opens Users, where replacing an existing code asks first.
         'action': 'Make a password recovery code', 'secondary': 'Replace it…' if code.get('has') else '', 'section': 'users',
         'find': '@make-recovery-code', 'secondaryFind': ''},
    ]
    if disk.get('encrypted'):
        rows.append({'title': 'Disk key', 'ready': bool(disk.get('recovery')),
                     'state': 'You have one.' if disk.get('recovery') else 'Not made yet.',
                     'action': 'Make a disk key', 'section': 'security', 'find': 'Disk key and unlocking'})
    backup_state = ('No backup for ' + str(backup['overdueDays']) + ' days.' if backup.get('overdueDays') else
                    'Last backup ' + (backup.get('lastText') or 'just now').split(' (')[0] + ', to ' + ((backup.get('drive') or {}).get('name') or 'your backup drive') + '.' if backup_ready else
                    "The last backup didn't finish." if backup.get('error') else
                    'No backup yet.' if backup.get('configured') else 'Not set up.')
    rows.append({'title': 'Backups', 'ready': backup_ready, 'state': backup_state,
                 'action': 'Open Backups' if backup.get('configured') else 'Set up backups', 'section': 'backups', 'find': ''})
    return rows


def main():
    parser = argparse.ArgumentParser(prog="starchaser safety", description=__doc__)
    parser.add_argument('command', nargs='?', choices=['status'], default='status')
    parser.parse_args()
    snapshots = read(['starchaser', 'recovery', 'list'])
    stick = read(['starchaser', 'recovery', 'usb', 'status'])
    code = read(['/usr/local/lib/starchaser/starchaser-admin', 'recovery-code-status'])
    security = read(['starchaser', 'security', 'status'])
    backup = read(['starchaser', 'backup', 'status'])
    disk = security.get('driveUnlock') or {}
    try:
        health = json.loads(Path('/var/lib/starchaser/drive-health.json').read_text())
    except (OSError, ValueError):
        health = {'state': 'unknown', 'message': "Drive health hasn't been checked yet."}
    print(json.dumps({'ok': True, 'items': checklist(snapshots, stick, code, disk, backup), 'backup': backup, 'health': health,
                      'onDisk': Path('/boot/loader/entries/starchaser-recovery.conf').is_file()}))


if __name__ == '__main__':
    main()
