#!/usr/bin/python3
"""Narrow root entry point for guided hibernate setup and its explicit test."""
import fcntl
import json
import os
import sys
import hibernate
import updater


def main(args):
    try:
        if os.geteuid() != 0: raise ValueError('Administrator authorization is required.')
        if len(args) != 1 or args[0] not in ('status', 'setup', 'test', 'confirm', 'hibernate'):
            raise ValueError('Choose status, setup, test, confirm, or hibernate.')
        if args[0] == 'status':
            # Read protected startup/firmware files without taking any write lock.
            # The matching polkit action permits only this exact read-only verb.
            print(json.dumps(hibernate.status()))
            return 0
        with open('/run/starchaser-hibernate.lock', 'w') as lock:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            if args[0] == 'setup':
                # Share the updater's lock and power inhibitor throughout startup-file writes.
                with updater.SystemChange('boot') as change:
                    result = hibernate.setup()
                    change.result = result
            elif args[0] in ('test', 'hibernate'):
                # Do not sleep during an update, and do not inhibit our own explicit sleep request.
                updater.open_dir(updater.RUN_DIR)
                with open(updater.RUN_DIR / 'run.lock', 'a') as system_lock:
                    fcntl.flock(system_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
                    result = getattr(hibernate, args[0])()
            else:
                result = hibernate.confirm()
            print(json.dumps(result))
            return 0
    except BlockingIOError:
        print(json.dumps(dict(ok=False, errors='An install, update, or hibernate setup is running. Wait for it to finish, then try again.')))
    except (OSError, ValueError, KeyError) as error:
        print(json.dumps(dict(ok=False, errors=str(error))))
    return 1


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