#!/usr/bin/python3 -I
# SPDX-License-Identifier: MIT
"""Root-only power configuration and one-shot hardware charge-limit restore."""
import fcntl
import os
from pathlib import Path
import sys
sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parent))
import power_settings

if __name__ == '__main__':
    try:
        if os.geteuid() != 0:
            raise PermissionError('Use ErdOS Settings with administrator authentication to save power settings.')
        values = sys.argv[1:]
        with open('/run/erdos-power.lock', 'a') as lock:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            if len(values) == 3 and values[0] == 'charge':
                print(power_settings.set_charge_limit(values[1], values[2]))
            elif len(values) == 2 and values[0] == 'restore-charge':
                power_settings.restore_charge_limit(values[1])
            else:
                power_settings.validate_lid(values)
                power_settings.save_lid(values)
                print('Lid behavior saved. Restart the computer to use these settings.')
    except BlockingIOError:
        print('Another power settings change is running. Try again after it finishes.', file=sys.stderr)
        sys.exit(1)
    except Exception as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
