#!/usr/bin/python3
# summary: Check or set up hibernation, then test resuming your work.
"""Usage: starchaser hibernate status | setup | test | confirm | hibernate

Setup needs administrator authorization. Restart after setup. Save work before test.
Confirm only after resuming with your open work intact. Secure Boot, encryption,
unsupported storage, or an unknown startup layout can prevent guided setup.
"""
import json
import subprocess
import sys


def main(args):
    if args in ([], ['--help'], ['-h']):
        print(__doc__)
        return 0
    try:
        # Native installs protect /boot. The exact read-only policy permits the
        # active local desktop to inspect it; changes still need authorization.
        if len(args) != 1 or args[0] not in ('status', 'setup', 'test', 'confirm', 'hibernate'):
            print(__doc__)
            return 2
        code = subprocess.run(['pkexec', '/usr/local/lib/starchaser/starchaser-hibernate-admin', args[0]]).returncode
        if args == ['status'] and code in (126, 127):
            print(json.dumps(dict(ok=False, errors='Hibernate can only be checked while sitting at this computer.')))
        return code
    except (OSError, ValueError, KeyError, subprocess.SubprocessError):
        print(json.dumps(dict(ok=False, errors="Hibernate support couldn't be checked. No changes were made.")))
        return 1


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